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 un开发者_运维知识库do it to get the char array back?
Thanks for your help.
EDIT: The third line was a typo - *mychararray should have been *mylong
- You're assuming
sizeof(long) == 4
, which can be wrong. (Especially on 64 bit platforms). If that assumption is broken, you're in undefined behavior territory: manipulatingmylong
will read/write beyondmychararray
's allocated memory. Your second line has no effect if you don't use*mylong
on the third line
You can get back a char*
with something like:
char *thing = reinterpret_cast<char*>(mylong);
(You should be using that type of cast in the first case also, it's more explicit than the C-type cast.)
Another thing to watch out for is the endianess of the CPU if multiple machines are involved. You'll end up with the chars reversed if they are different.
Yes, it should conceptually work. Such casts however make assumptions about the underlying platform. If, you are however using C++, I would suggest that you use a C++ typecast.
reinterpret_cast
is specifically for your case.
精彩评论