-3

Please read my question carefully, then judge if it is duplicate

I am green. If there is any mistake in my description please help me figure it out

I want to parse a binary file by java. the first pic is the file opened by hex editor, you can see from 000000 0 to 000000 3 is ef ef ef ef

enter image description here

here is my code

String filepath = "D:\\CHR_2_20151228132500.dat.gz";
File file = new File(filepath);
FileInputStream fis = new FileInputStream(file);

GZIPInputStream gzip = new GZIPInputStream(fis);

DataInputStream din = new DataInputStream(gzip);

byte[] bytes = new byte[20];

din.read(bytes, 0, 4);

for (byte b : bytes) {
    String str  = Integer.toHexString(b);
    System.out.print(str);
}

this is the result I parse you can see there is ffffff between each ef and several zero appended

enter image description here

I want get data as same as it in hex editor.how can I get this ?

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42
Wangbo
  • 325
  • 7
  • 18
  • Don't post pictures of text here: post the text; and don't use quote formatting for text that isn't quoted. – user207421 Feb 23 '16 at 03:55

1 Answers1

1
String str  = Integer.toHexString(b);

Bytes are signed in Java. You need:

String str  = Integer.toHexString(b & 0xff);

And then to ensure two digits you need:

String str  = Integer.toHexString((b & 0xff)+256).substring(1);
user207421
  • 305,947
  • 44
  • 307
  • 483