-1

I have a string which I want to cast to a byte array, however, my string is the actually representation of an image byte array (eg. String x = "00123589504e47..."). So, I'm stuck because doing x.getBytes(); doesn't do the job.. I need a way to cast the string to byte array and then save that byte array to an image in a specific directory. How can I cast it?

yat0
  • 967
  • 1
  • 13
  • 29
  • 3
    *my string is the actually representation of the byte array*: what does that mean? Be precise. Suppose the bytes are 1, -6, and 124. What would the corresponding String be? – JB Nizet Jan 21 '15 at 12:16
  • Show us an input string and expected output. – default locale Jan 21 '15 at 12:17
  • the string never gets that values.. The string is always a byte representation of an image. So, I need to cast that string to byte array and then save the image in the directory I want. @JBNizet – yat0 Jan 21 '15 at 12:18
  • 2
    If it's encoded in base16, see this question: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java – jontro Jan 21 '15 at 12:18
  • 2
    That doesn't make any sense. A byte is a number whose value can go from -128 to 127. An image file can contain any of these values. How do you create the String from the bytes of the image? – JB Nizet Jan 21 '15 at 12:19
  • 2
    "byte representation" is ambiguous. There's more than one way to represent byte array as string. Please, specify the exact format of your string. – default locale Jan 21 '15 at 12:25

2 Answers2

1

doing x.getBytes(); doesn't do the job

Yes, that's normal...

A char and a byte have no relationship to one another; you cannot seamlessly cast from one to the other and expect to obtain a sane result. Read about character codings.

From what you want, it appears that the String is in fact a "hex dump" of the image. You therefore need to read two chars by two chars and convert that to a byte array.

How? Well, you have hints. First, the length of the resulting byte array will always be that of the string divided by 2, so you can do that to start with:

// input is the string
final int arrayLen = input.length() / 2;
final byte[] result = new byte[arrayLen];

Then you need to walk through the string's characters and parse those two characters into a byte, and add that to the array:

int strIndex;
char[] chars = new char[2];

for (int arrayIndex = 0; arrayIndex < arrayLen; arrayIndex++) {
    strIndex = 2 * arrayIndex;
    chars[0] = input.charAt(strIndex);
    chars[1] = input.charAt(strIndex + 1);
    result[arrayIndex] = Byte.parseByte(new String(chars), 16);
}

// Done
return result;
fge
  • 119,121
  • 33
  • 254
  • 329
1

I always use this one liner:

   byte[] data = DatatypeConverter.parseHexBinary(x);

You can then instantiate a FileOutputStream for the image and write the bytes onto that.

Aaryn Tonita
  • 490
  • 3
  • 7