Reputation: 2841
I am programming a little Java based Android app that receives a c based unsigned char[] byte array from a Bluetooth chip and streams it into a byte array.
The fact that it is Android and Bluetooth shouldn't matter though, it is just background. But, I am using minimum API 8 if that makes a difference.
The main code is:
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
bytesRead = dis.read(buffer, 0, 1024);
However, when I look at the actual contents of the buffer, I see this:
[0] 15 [0xf] [^O]
[1] 15 [0xf] [^O]
[2] 0 [0x0] [^@ (NUL)]
[3] -119 [137] [0x89] [^É]
[4] 2 [0x2] [^B]
[5] 6 [0x6] [^F]
[6] 26 [0x1a] [^Z]
[7] -47 [209] [0xd1] [Ñ]
[8] -1 [255] [0xff] [ÿ]
[9] 104 [0x68] [h]
[10] -1 [255] [0xff] [ÿ]
[11] -46 [210] [0xd2] [Ò]
[12] -1 [255] [0xff] [ÿ]
[13] 104 [0x68] [h]
[14] -19 [237] [0xed] [í]
[15] -128 [128] [0x80] [^À]
The above is a copy from the eclipse Expression view set to show
My question is, if this is a byte array, why are some of the Hex values containing 2 bytes. Look at elements 6 through 14, each of them are of the form 0x1a, 0x12, 0xff, etc. The bytes 0 through 5 are all one byte (except for element 3).
I don't think this is an issue from the Bluetooth side because I see the actual code being made, and its an unsigned char[] array, each element is only one byte. Plus, I recall seeing something like this in a previous little project that involved taking data streams from an online API.
How can I ensure the Java array elements contain only 1 byte? And for that matter, I feel like I am not understanding something important about Java since this perplexes me -- how can Java allow a byte array to contain more than one byte per element?
Upvotes: 1
Views: 613
Reputation: 691635
You're confusing bytes and hexadecimal digits.
A byte contains 8 bits. An hexadecimal digit goes from 0 to F, and is thus only 4 bits (16 values, 16 = 2^4, thus 4 bits). A single byte is thus represented using two hexadecimal digits.
0xf
is equivalent to 0x0f
. The first 4 bits are all 0, and the last 4 bits are all 1.
Upvotes: 5
Reputation: 7784
A byte is 8 bits and so can hold 0 - (2^8 - 1) i.e. 0-255 (0x0 - 0xff). All your values are a single byte.
Upvotes: 0