Convert a string representation of a hex dump to a

2018-12-31 00:15发布

I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.

I couldn't have phrased it better than the person that posted the same question here.

But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the

byte[] {0x00,0xA0,0xBf}

what should I do?

I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple.

标签: java byte hex dump
25条回答
时光乱了年华
2楼-- · 2018-12-31 00:58

I know this is a very old thread, but still like to add my penny worth.

If I really need to code up a simple hex string to binary converter, I'd like to do it as follows.

public static byte[] hexToBinary(String s){

  /*
   * skipped any input validation code
   */

  byte[] data = new byte[s.length()/2];

  for( int i=0, j=0; 
       i<s.length() && j<data.length; 
       i+=2, j++)
  {
     data[j] = (byte)Integer.parseInt(s.substring(i, i+2), 16);
  }

  return data;
}
查看更多
登录 后发表回答