I'm trying to do bit arithmetic with variables a
and b
. When I reverse a
, which has the value 0xAF, the result shows as 8 digits.
Unlike the others that show as 2 digits.
I don't know why it happens, but guess that it is relevant to %x
's showing way and little endian?
Here is my code:
#include <stdio.h>
int main()
{
int a = 0xAF; // 10101111
int b = 0xB5; // 10110101
printf("%x \n", a & b); // a & b = 10100101
printf("%x \n", a | b); // a | b = 10111111
printf("%x \n", a ^ b); // a ^ b = 00011010
printf("%x \n", ~a); // ~a = 1....1 01010000
printf("%x \n", a << 2);// a << 2 = 1010111100
printf("%x \n", b >> 3); // b >> 3 = 00010110
return 0;
}
Considering your int a
is most likely 32 bit in size, your a
actually looks like this:
int a = 0xAF; // 0000 0000 0000 0000 0000 0000 1010 1111
So if you flip all the bits on that, you have
1111 1111 1111 1111 1111 1111 0101 0000
Or, in hex
0xFFFFFF50
Which is exactly what you're getting. The others show only 2 digits because trailing zeroes are omitted when printing hex, and your other bit operations do not in fact change any of the leading zeroes.
---- Credit to @ chqrlie for this ---- If you really only want to see 8 bits of the result, you can do
printf("%hhx \n", ~a); // ~a = 1....1 01010000 --> Output : 50
Which restricts the printed value to unsigned char
(8 bit [on modern os, not guaranteed, but very likely for your purposes]) length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With