I defined an uint8_t
variable x and gave it the value 11110000
, but when I print it (casting it to an unsigned integer so it's not invisible), it prints out 112
when it should be 240
. What did I do wrong ?
Also, I only need 4 bits, but I don't know any types which could provides me only 4 bits, which is why I use an uint8_t
.
Brief code :
std::uint8_t walls;
walls=11110000;
cout << (unsigned int) walls <<endl;
11110000
is being interpreted as a decimal number.
Which its binary representation is:
1010 1001 1000 0110 0111 0000
Since your variable is unsigned and overflow causes wrap around, the lower 8 bit are being assigned
0111 0000
Which is 112.
To use binary constants , simply add 0b
as suggested in comments.
walls=0b11110000
And apparently this is part of C++14. Thanks to @Daniel Kamil Kozar.
What did I do wrong ?
You didn't assign a base 2 value but a base 10 as you thought here:
walls=11110000;
To assign base 2 values use (at least with c++14 standard)
walls=0b11110000;
For older standards you can use
walls=0xF0;
Also, I only need 4 bits, but I don't know any types which could provides me only 4 bits, which is why I use an uint8_t.
In fact uint8_t
is the smallest number of bits you can have.
But you probably want to mask and only use the lower nibble:
walls=0b000011111;
or again for pre c++14:
walls=0x0F;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.