Shift count negative or too big error - correct solution?

Posted by PeterK on Stack Overflow See other posts from Stack Overflow or by PeterK
Published on 2010-06-11T07:22:01Z Indexed on 2010/06/11 7:22 UTC
Read the original article Hit count: 478

Filed under:
|
|

I have the following function for reading a big-endian quadword (in a abstract base file I/O class):

unsigned long long CGenFile::readBEq(){
  unsigned long long qT = 0;
  qT |= readb() << 56;
  qT |= readb() << 48;
  qT |= readb() << 40;
  qT |= readb() << 32;
  qT |= readb() << 24;
  qT |= readb() << 16;
  qT |= readb() << 8;
  qT |= readb() << 0;
  return qT;
}

The readb() functions reads a BYTE. Here are the typedefs used:

typedef unsigned char   BYTE;
typedef unsigned short  WORD;
typedef unsigned long   DWORD;

The thing is that i get 4 compiler warnings on the first four lines with the shift operation:

warning C4293: '<<' : shift count negative or too big, undefined behavior

I understand why this warning occurs, but i can't seem to figure out how to get rid of it correctly. I could do something like:

qT |= (unsigned long long)readb() << 56;

This removes the warning, but isn't there any other problem, will the BYTE be correctly extended all the time? Maybe i'm just thinking about it too much and the solution is that simple. Can you guys help me out here? Thanks.

© Stack Overflow or respective owner

Related posts about c++

Related posts about arithmetic