1

I have a unsigned int that was converted to a signed char like this

  unsigned int b = 128;
  char a[4];    

  a[0] = b >> 24;
  a[1] = b >> 16;
  a[2] = b >> 8;
  a[3] = b >> 0;

Without knowing what value of b is, can I get back the number? The method below fails for numbers greater than 128. It seems like there is some ambiguity to getting the number back from the array.

  unsigned int c = 0;  
  c += a[0] << 24;
  c += a[1] << 16;
  c += a[2] << 8;
  c += a[3];

  cout<<c<<endl;
user1161604
  • 353
  • 3
  • 4
  • 10

2 Answers2

1
unsigned int c = ((a[0] << 24) & 0xFF000000U)
               | ((a[1] << 16) & 0x00FF0000U)
               | ((a[2] <<  8) & 0x0000FF00U)
               | ( a[3]        & 0x000000FFU);

or

unsigned int c = unsigned(a[0]) << 24
               | unsigned(a[1]) << 16
               | unsigned(a[2]) <<  8
               | unsigned(a[3]);
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

Converting signed to unsigned is not advised. If you do want to do it, you have to do it manually. Not easy, AFAIK.

Have a look at this question.

Community
  • 1
  • 1
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415