blipman17 blipman17 - 1 year ago 89
C++ Question

bitshifting unsigned char and unsigned long long gone wrong

This is a function I (want to) use to decode numbers out of unsigned char[] buffers for networking.

inline unsigned long long getULongLongLongInt(const unsigned char* buffer)
unsigned long long number= (buffer[0] << 56);
number|= (buffer[1] << 48);
number|= (buffer[2] << 40);
number|= (buffer[3] << 32);
number|= (buffer[4] << 24);
number|= (buffer[5] << 16);
number|= (buffer[6] << 8);
number|= buffer[7];
return number;

I'm getting warning C4293 '<<': shift count negative or too big, undefined behaviour" four times for the most upper bitshifts;
Is this a warning I can safely ignore because the compiler doesn't recognise I'm using an unsigned 64 bit int? I presume it isn't. But then how do I fix this?

Answer Source

No, you can't ignore it. The operand buffer[i] is of type unsigned char, which is probably promoted to int (and if not int, then unsigned int). If 56 is greater than or equal to the bit width of int, then the shift is UB.

You need to write static_cast<unsigned long long>(buffer[0]) << 56 and so on, so the operand will be at least 64 bits long before the shift.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download