1

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;
2
  • 1
    byte in Java is signed. It's range is - [-128, 127], the value after 127 goes to the negative side. And hence 228 is -28. Commented Dec 13, 2012 at 9:05
  • 1
    Please don't use DataInputStream to read text vanillajava.blogspot.co.uk/2012/08/… Commented Jan 30, 2013 at 20:50

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 But it still matters though even if you are treating them as bits and are not just debugging. Why oh why does java have signed... I don't buy the explanation :P
1

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.

2 Comments

chances are he has a good reason to want an array of bytes (i.e. input to some other API call). The only real reason to convert to an unsigned int is for presentation purposes, which should be separated from the internal representation.
do also note that storing as int will require four times more memory than storing them in a byte array...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.