0

this seems to be working well for me except this one time. I'm trying to get the first 10 bits of this number

unsigned char c= 17512807u<<22>>22;

I expect this to be 359 or 0101100111 but I'm getting 103 or 0001100111. Is there a reason that this is happening?

4
  • An unsigned character is 8 bits, so it can only contain values between 0 and 255. The value of 359 you want cannot fit in an unsigned char. Commented Sep 30, 2017 at 22:21
  • 0101100111 is 10 bits. unsigned char is 8 (probably). Commented Sep 30, 2017 at 22:21
  • Assuming ints are 32-bits in your machine, this should give you the low-order 10 bits, not the high-order ("first") 10 bits. The result will be truncated to 8 bits when stored in c (assuming 8-bit characters). Commented Sep 30, 2017 at 22:21
  • Notem it is not bad to put u in 17512807u, but it is not needed. Commented Oct 1, 2017 at 0:00

1 Answer 1

1

The result you are getting is correct due to the truncation to 8-bit unsigned char value (when assigning to c).

If you need a value that is 10-bits wide you should use a different datatype, like uint16_t or an unsigned int.

Reference to C++ integer datatypes

Sign up to request clarification or add additional context in comments.

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.