3

I need to prepend the string "00" or byte 0x00 to the beginning of a byte array? I tried to do it with a for loop but when I convert it to hex it doesn't show up in the front.

italiano40
  • 496
  • 9
  • 18
  • 1
    If it's actually byte[], you can use Arrays.copy(...) to fill slots 1-(n+1) with your original array and then fill slot 0 with 0x00. – Thomas Jul 04 '12 at 03:32

1 Answers1

6

The string "00" is different than the number 0x00 when converted to Bytes. What is the data type you are trying to prepend to your byte array? Assuming it's a Byte representation of the string "00", try the following:

bytes[] orig = <your byte array>;  
String prepend = "00";  
bytes[] prependBytes = prepend.getBytes();  
bytes[] output = new Bytes[prependBytes.length + orig.length];

for(i=0;i<prependBytes.length;i++){
    output[i] = prependBytes[i];
}

for(i=prependBytes.length;i<(orig.length+prepend.lenth);i++){
  output[i] = orig[i];
}

or you can use Arrays.copy(...) instead of the two for loops as mentioned before to do the prepending. See How to combine two byte arrays

Alternativly, if you are trying to literally prepend 0 to your byte array, decalare prependBytes in the following way and use the same algorithm

byte[] prependBytes = new byte[]{0,0};

Also you say that you're converting your byte array to hex, and that may truncate leading zeros. To test this, try prepending the follwoing and converting to hex and see if there is a different output:

byte[] prependBytes = new byte[]{1,1};

If it is removing the leading zeros that you want, you may wish to convert your hex number to a string and format it.

Tucker
  • 7,017
  • 9
  • 37
  • 55
  • That doesn't add 00, that adds "0303" to the beginning of all my hashed bytes. It also overwrites first for characters of the hash, I am also using BigInteger to convert it from bytes to a string by using new BigInteger(bytearray).toString(16); – italiano40 Jul 04 '12 at 04:12
  • Thats because the 0303 is the probably the byte representation of the String "00". I think I know what you're trying to do tho... I'll edit my Answer in a bit with my thoughts – Tucker Jul 04 '12 at 04:14
  • 1
    @italiano40 'That adds "0303" to the beginning of all my hashed byte'. No it doesn't, it adds 0x3030 to the beginning, which is the byte representation of "00", which is exactly what you asked for. If what you want is really 0x0 0x0, adjust the code accordingly. – user207421 Jul 04 '12 at 05:49
  • I think there's a mistake in your example. Shouldn't `output[i] = orig[i];` be `output[i] = orig[i-prependBytes.length];` so as to not go out of bounds on the index? – OscarVanL Nov 03 '20 at 22:02
  • Typos: `byte[] orig = ; ` `byte[] prependBytes = new byte[]{0,0};` `byte[] output = new byte[prependBytes.length + orig.length];` `for(int i=0;i – djp3 Jul 20 '22 at 23:35