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;
1
  • You need an unsigned char array. Commented Feb 12, 2012 at 18:42

2 Answers 2

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]);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.