Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to char array and then convert it back

Tags:

c++

casting

I am a little confused on how casts work in C++.
I have a 4 bytes integer which I need to convert to a char[32] and then convert it back in some other function.

I am doing the following :

uint32_t v = 100;
char ch[32]; // This is 32 bytes reserved memory
memcpy(ch,&v,4);
uint32_t w = *(reinterpret_cast<int*>(ch)); // w should be equal to v 

I am getting the correct results on my compiler, but I want to make sure if this is a correct way to do it.

like image 370
Rajesh Avatar asked Sep 06 '26 02:09

Rajesh


1 Answers

Technically, no. You are at risk of falling foul of your CPU's alignment rules, if it has any.

You may alias an object byte-by-byte using char*, but you can't take an actual char array (no matter where its values came from) and pretend it's some other object.

You will see that reinterpret_cast<int*> method a lot, and on many systems it will appear to work. However, the "proper" method (if you really need to do this at all) is:

const auto INT_SIZE = sizeof(int);
char ch[INT_SIZE] = {};

// Convert to char array
const int x = 100;
std::copy(
   reinterpret_cast<const char*>(&x),
   reinterpret_cast<const char*>(&x) + INT_SIZE,
   &ch[0]
);

// Convert back again
int y = 0;
std::copy(
   &ch[0],
   &ch[0] + INT_SIZE,
   reinterpret_cast<char*>(&y)
);

(live demo)

Notice that I only ever pretend an int is a bunch of chars, never the other way around.

Notice also that I have also swapped your memcpy for type-safe std::copy (although since we're nuking the types anyway, that's sort of by-the-by).

like image 64
Lightness Races in Orbit Avatar answered Sep 08 '26 20:09

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!