I have the following function:
void func(unsigned long v)
{
char max_byte = 0xFF;
char buffer[8];
buffer[0] = static_cast<char>((v) & max_byte);
buffer[1] = static_cast<char>((v >> 8) & max_byte);
buffer[2] = static_cast<char>((v >> 16) & max_byte);
buffer[3] = static_cast<char>((v >> 24) & max_byte);
buffer[4] = static_cast<char>((v >> 32) & max_byte);
buffer[5] = static_cast<char>((v >> 40) & max_byte);
buffer[6] = static_cast<char>((v >> 48) & max_byte);
buffer[7] = static_cast<char>((v >> 56) & max_byte);
}
which takes an unsigned long
argument and insert its 8 bytes to char
buffer ( don't try to figure out why. it is a concise version of a meaningful function).
This code compiles well on 64 bit but on 32 bit I get the following warning:
warning: right shift count >= width of type
referring to lines:
buffer[4] = static_cast<char>((v >> 32) & max_byte);
buffer[5] = static_cast<char>((v >> 40) & max_byte);
buffer[6] = static_cast<char>((v >> 48) & max_byte);
buffer[7] = static_cast<char>((v >> 56) & max_byte);
I think I understand the warning but I'm not sure what should I do to be able to compile it smoothly on 32 bit as well.
unsigned long
is only guaranteed to have 32 bits. See here. You need to use unsigned long long
to have 64 bits guaranteed.
Even better would be to use a fixed width integer, i.e. uint64_t
. They are defined in header <cstdint>
(or <stdint.h>
).