开发者

Char array to long to char array [duplicate]

开发者 https://www.devze.com 2023-03-13 09:59 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Converting a four character string to a long
This question already has answers here: Closed 11 years ago.

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


  1. 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: manipulating mylong will read/write beyond mychararray's allocated memory.
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消