www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: 4-character literal

Rick Mann Wrote:

 
 Hi. I'm porting some Mac OS X (Carbon) code, and it relies heavily on a
language feature that's been used on the Mac for decades: 4-byte character
literals (like 'abcd'). In this case, I'm setting up enums that will be passed
to OS APIs as 32-bit unsigned int parameters:
 
 enum : uint
 {
     kSomeConstantValue = 'abcd'
 }
 

Here's some sample code based off of Gregor Richards' and Joel's ideas. I had to do a little reversing logic which showed that they both gave the exact same results. (On Intel, numbers have their bits stored in the revese order...so to me, Gregor's original way seemed more correct for creating a number from a string). // char4.d // dmd v1.003 WinXP SP2 union Converter { uint asInt; char[4] chr; } const Converter kSomeConstantValue = { chr : "abcd" }; const Converter kSomeConstantValueRev = { chr : "dcba" }; private import std.stdio; int main() { // Joel writefln("kSomeConstantValue.asInt=%d", kSomeConstantValue.asInt); // Gregor Richards idea (Reversed to equal Joel's output) writefln("a+b<<8+c<<16+d<<24=%d", (cast(uint)'a') + (cast(uint)'b' << 8) + (cast(uint)'c' << 16) + (cast(uint)'d' << 24)); writefln(); writefln("******"); writefln(); // Joel's reverse to equal Gregor's output writefln("kSomeConstantValueRev.asInt=%d", kSomeConstantValueRev.asInt); // Gregor Richards original idea (Intel's numerical reverse storage) writefln("a<<24+b<<16+c<<8+d=%d", (cast(uint)'a' << 24) + (cast(uint)'b' << 16) + (cast(uint)'c' << 8) + (cast(uint)'d')); return 0; } Output: ------------ C:\dmd>dmd char4.d C:\dmd\bin\..\..\dm\bin\link.exe char4,,,user32+kernel32/noi; C:\dmd>char4 kSomeConstantValue.asInt=1684234849 a+b<<8+c<<16+d<<24=1684234849 ****** kSomeConstantValueRev.asInt=1633837924 a<<24+b<<16+c<<8+d=1633837924 C:\dmd> David L.
Jan 26 2007