Trung Nguyen
Trung Nguyen

Reputation: 177

int to unsigned char* and vice versa

I am new to C/C++. After a long research, I need your help for this. I just want to store a number in unsigned char* and then bring the number back.

int nu = 50;
unsigned char byteArray[sizeof(int)];
memcpy(byteArray, &nu, sizeof(int));

int newNu = reinterpret_cast<int>(byteArray);

Im expecting the newNu will be 50, instead, it's not. Could anybody show me where am I wrong?

For the int->unsign char* I think I was correct, but how to reverse the progress? is it the right way? btw, I compiled this on Visual Studio

Upvotes: 0

Views: 2291

Answers (2)

Alex Lop.
Alex Lop.

Reputation: 6875

Don't do it!!!

But in case you are just experiencing...

This part is incorrect:

int newNu = reinterpret_cast<int>(byteArray);

You are casting the address of the char array to int which is definitely not 50...

This is the code to get what you expect:

int newNu = *reinterpret_cast<int*>(byteArray);

Also pay attention to the parameters order in memcpy... It should be

memcpy(&newNu, byteArray, sizeof newNu);

Upvotes: 1

M.M
M.M

Reputation: 141618

Your cast converts the address of the array into a number.

The correct way to get the value out is:

int newNu;
memcpy(&newNu, byteArray, sizeof newNu);

Note: a naive attempt would be:

newNu = *reinterpret_cast<int *>(byteArray);

however this violates the strict aliasing rule, as well as potentially being an alignment violation. Do not do this. Warning: You may see this mistake repeated in various (not very good) references.

Upvotes: 7

Related Questions