Sachin K S
Sachin K S

Reputation: 99

converting hexadecimal to byte in java

I m new in java.I have a text document with hexadecimal values line by line, i m trying to read it and convert it into byte array. but for the hexadecimal values like 8, d, 11, 0, e4 when parsing i m getting wrong value for e4 as -28 instead of 228. how can i overcome this conversion error....

          FileInputStream fstream = new FileInputStream("C:/Users/data.txt");

          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(newInputStreamReader(in,"UTF-8"));


          byte[] bytes = new byte[1024];
          String str;
          int i=0;

          while ((str = br.readLine()) != null) 
          {

              bytes[i]= (byte) (Integer.parseInt(str,16) & 0xFF);
              i++;

          }
          byte[] destination = new byte[i];
          System.arraycopy(bytes, 0, destination, 0, i);

          br.close();
          return destination;

Upvotes: 1

Views: 3816

Answers (2)

Shantanu Banerjee
Shantanu Banerjee

Reputation: 1447

As Alnitak said byte is signed in java. Value of 0xe4 = 228 which is unsigned, and the range of byte is -128 to 127.

My suggestion is to use int instead of byte like

int[] bytes = new int[1024];
bytes[i]= Integer.parseInt(str,16);

You get the same thing which you have require.

Upvotes: 1

Alnitak
Alnitak

Reputation: 339816

Bytes (and all other integer types) are signed in Java, not unsigned.

If you're just treating the bytes as a byte array, it doesn't matter that some of the values are negative, their bit representation is still correct.

You can get the "proper" unsigned value by masking the byte value with the int value 0xff, although the resulting value will itselt be an int too:

int n = (myByte & 0xff);

Upvotes: 5

Related Questions