Reputation:
String message = "1";
byte[] bytes = message.getBytes();
System.out.println(bytes[0] + ": ");
for (int i = 0; i < 8; i++) {
System.out.print((bytes[0] >> (7 - i)) + " ");
}
Output: 49:
0 0 1 3 6 12 24 49
So my string is 1
which in ASCII is 49
. What I'm trying to understand is why do my bits have values 3,6,12,24 and 49? What's happening behind, why aren't they only 0 and 1 like the first 3?
Upvotes: 0
Views: 68
Reputation: 6525
Your actual data might be 49 but, it needs to fill 8 bit for byte data types.So, if you count 8 bit starting from 0 to 7 (as per your loop).And you are using >>
which will right shift.
49 binary is 0 0 1 1 0 0 0 1
0 0 1 1 0 0 0 1 >> 7-0 = 00000000 = 0
0 0 1 1 0 0 0 1 >> 7-1 = 00000000 = 0
0 0 1 1 0 0 0 1 >> 7-2 = 00000001 = 1
0 0 1 1 0 0 0 1 >> 7-3 = 00000011 = 3
0 0 1 1 0 0 0 1 >> 7-4 = 00000110 = 6
0 0 1 1 0 0 0 1 >> 7-5 = 00001100 = 12
0 0 1 1 0 0 0 1 >> 7-6 = 00011000 = 32
0 0 1 1 0 0 0 1 >> 7-7 = 00110001 = 49
Upvotes: 0
Reputation: 477794
When shifting, you shift the bits n
positions (in this case to the right).
So:
Loop# 7-i bits result
0 7 000000000 0
1 6 000000000 0
2 5 000000001 1
3 4 000000011 3
4 3 000000110 6
5 2 000001100 12
6 1 000011000 24
7 0 000110001 49
The reason why the first shifts are 0
and 1
is because al significant bits were already shifted out.
If you want to obtain the last bit, you need to perform (a>>s)&1
with a
the number and s
the bit from right you want.
In case you want to print the binary representation of a
, you can simply use Integer.toBinaryString(a);
Upvotes: 0
Reputation: 727077
The last 8 bits of number 49
in binary looks like this:
00110001
When you shift the number right by k
bits, it's the same as dividing it in int
by 2k. That is what you get in the output (digits to the right of |
are dropped):
0 | 0110001 -- 0
00 | 110001 -- 0
001 | 10001 -- 1
0011 | 0001 -- 3
00110 | 001 -- 6
001100 | 01 -- 12
0011000 | 1 -- 24
00110001 | -- 49
Upvotes: 1
Reputation: 178343
Because your bit extraction is incorrect. The bit representation for the character '1'
is that of 49
: 00110001
.
You are shifting 7 times, then 6, then 5, etc., but you are not isolating the bits properly.
00110001 >> 7 is 00000000 or 0
00110001 >> 6 is 00000000 or 0
00110001 >> 5 is 00000001 or 1
00110001 >> 4 is 00000011 or 3
00110001 >> 3 is 00000110 or 6
00110001 >> 2 is 00001100 or 12
00110001 >> 1 is 00011000 or 24
00110001 >> 0 is 00110001 or 49
You must do a bitwise-and with 1
to isolate the bit you've shifted to get the 1s and 0s out.
System.out.print( ((bytes[0] >> (7 - i)) & 1) + " ");
Output:
49:
0 0 1 1 0 0 0 1
Upvotes: 2
Reputation: 280181
49 in binary is
110001
You shift this same value by 7, 6, 5, 4, ..., (7 - i)
bits.
So
00110001 >> 7 ==> 00000000 == 0
00110001 >> 6 ==> 00000000 == 0
00110001 >> 5 ==> 00000001 == 1
00110001 >> 4 ==> 00000011 == 3
...
You can use Integer.toBinaryString(int)
to get the binary representation of an integer value as a String
.
Upvotes: 4