wrote:
> I casted an 8 ints to byte types. Some of them come out in the right
> format, but when I print them, some come out way bigger than 8 bits.
>
> Here is the string representation of the byte [8] array:
>
> 1111111111111111111111110000101 1111111111111111111111111101000 10011
> 1010100 1111 1010 1111111111111111111111110110100 101
>
> How can I truncate off the extra 1's to just get the last 8 bits of
> values [0], [1], and [6]?
All numerical types are signed (except char). Before any arithmetic on
byte, char or short is performed the value is transformed into an int.
Consider the byte -1, which is 11111111 in binary. If you wanted to see
if bit n of byte b is set you might try (b & (1<<n)) != 0. If b is
11111111 (binary) then it is first converted to the int
11111111111111111111111111111111 (binary). So, you need to either remove
or ignore the top 24 bits.
You can remove all but the bottom eight bits of an int, i, with i &
0xff. So to get an unsigned binary representation of a byte, b, you can
use Integer.toBinaryString(b & 0xff).
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/