Possible Duplicate:
Converting a four character string to a long
I want to convert a char array to a long and back again but I’m a bit stuck.
This is a fragment of the code I’ve got so far:
char mychararray[4] = {'a', 'b', 'c', 'd'};
unsigned long * mylong = (unsigned long *)&mychararray;
cout << *mylong << endl;
Which should take the char array, and represent the first 4 bytes (the length of a long) as a long (I think).
Is this correct? And how would I undo it to get the char array back?
Thanks for your help.
EDIT: The third line was a typo – *mychararray should have been *mylong
sizeof(long) == 4, which can be wrong. (Especially on 64 bit platforms). If that assumption is broken, you’re in undefined behavior territory: manipulatingmylongwill read/write beyondmychararray‘s allocated memory.Your second line has no effect if you don’t use*mylongon the third lineYou can get back a
char*with something like:(You should be using that type of cast in the first case also, it’s more explicit than the C-type cast.)