0

I have a byte array of length 14. Can I combine 1st two elements into one and so on, to make its size 7? i.e. <{730C5454000160}> should look like

<{73,0C,54,54,00,01,60}>.

OR if not I have a string "730C5454000160", I need it as array of byte like

<{73,0C,54,54,00,01,60}>.

Please some one help me out, thanks.

user unknown
  • 35,537
  • 11
  • 75
  • 121
sreekanthnu
  • 9
  • 1
  • 2
  • 3
    I think you are looking for "convert hex string to byte array", but I could be wrong,.. –  Jun 20 '12 at 06:44
  • What have you tried? It's always best if you try a few things before asking for help, and if you show us what you've tried, we can help to steer you in the right direction. – Cat Jun 20 '12 at 06:45
  • http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java – Samy Vilar Jun 20 '12 at 06:46
  • @nhahtdh except if you know how. See my answer for the "how" – Bohemian Jun 20 '12 at 06:59
  • @Bohemian: I was thinking of something else when I comment that. Regards your solution, I think it is sufficient for the sample case, but it will be more extensible with BigInteger. – nhahtdh Jun 20 '12 at 07:13

1 Answers1

3

Let the JDK help you:

byte[] bytes = new byte[7];
System.arraycopy( ByteBuffer.allocate(8).putLong( Long.parseLong( s, 16 ) ).array(), 1, bytes, 0, 7);

Here's some test code:

public static void main( String[] args ) {
    String s = "730C5454000160";

    byte[] bytes = new byte[7];
    System.arraycopy( ByteBuffer.allocate(8).putLong( Long.parseLong( s, 16 ) ).array(), 1, bytes, 0, 7);

    System.out.println( Arrays.toString(bytes ));
}

Output:

[115, 12, 84, 84, 0, 1, 96]
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • @Goku what do you mean? – Bohemian Feb 03 '15 at 22:01
  • Bohemian I means if I store bytes of file into byte array and try to reduce the size with the array without any change in data so Is it work same as working for the String ? – Simmant Feb 04 '15 at 10:12
  • 1
    @goku yes, it will work - bytes are bytes. In this example, the String was used only as a source of bytes. You can get the bytes from anywhere you like. – Bohemian Feb 04 '15 at 14:17