This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert a string representation of a hex dump to a byte array using Java?
For example, I have a string "DEADBEEF". How can I convert it to byte[] bytes = { 0xDE, 0xAD, 0xBE, 0xEF } ?
Loop through each pair of two characters and convert each pair individually:
byte[] bytes = new byte[str.length()/2];
for( int i = 0; i < str.length(); i+=2 )
bytes[i/2] = ((byte)Character.digit(str.charAt(i),16))<<4)+(byte)Character.digit(str.charAt(i),16);
I haven't tested this code out (I don't have a compiler with me atm) but I hope I got the idea through. The subtraction/addition simply converts 'A' into the number 10, 'B' into 11, etc. The bitshifting <<4 moves the first hex digit to the correct place.
EDIT: After rethinking it a bit, I'm not sure if you're asking the correct question. Do you want to convert "DE" into {0xDE}, or perhaps into {0x44,0x45} ? The latter is more useful, the former is more like a homework problem type question.
getBytes() would get you the bytes of the characters in the platform encoding. However it sounds like you want to convert a String containing a Hex representation of bytes into the actual represented byte array.
In which case I would point you toward this existing question: Convert a string representation of a hex dump to a byte array using Java? (note: I personally prefer the 2nd answer to use commons-codec but more out of philosophical reasons)
You can parse the string to a long and then extract the bytes:
String s = "DEADBEEF";
long n = Long.decode( "0x" + s ); //note the use of auto(un)boxing here, for Java 1.4 or below, use Long.decode( "0x" + s ).longValue();
byte[] b = new byte[4];
b[0] = (byte)(n >> 24);
b[1] = (byte)(n >> 16);
b[2] = (byte)(n >> 8);
b[3] = (byte)n;
tskuzzy's answer might be right (didn't test) but if you can, I'd recommend using Commons Codec from Apache. It has a Hex class that does what you need.
Related
I have the following problem in Java. I am using an encryption algorithm that can produce negative bytes as outcome, and for my purposes I must be able to deal with them in binary. For negative bytes, the first or most significant bit in the of the 8 is 1. When I am trying to convert binary strings back to bytes later on, I am getting a NumberFormatException because my byte is too long. Can I tell Java to treat it like an unsigned byte and end up with negative bytes? My code so far is this:
private static String intToBinByte(int in) {
StringBuilder sb = new StringBuilder();
sb.append("00000000");
sb.append(Integer.toBinaryString(in));
return sb.substring(sb.length() - 8);
}
intToBinByte(-92); // --> 10100100
Byte.parseByte("10100100", 2) // --> NumberFormatException
Value out of range. Value:"10100100" Radix:2
Is there a better way to parse signed Bytes from binary in Java?
Thanks in advance!
You can just parse it with a larger type, then cast it to byte. Casting simply truncates the number of bits:
byte b = (byte) Integer.parseInt("10100100", 2);
I have written the following function to solve the problem:
private static byte binStringToByte(String in) {
byte ret = Byte.parseByte(in.substring(1), 2);
ret -= (in.charAt(0) - '0') * 128;
return ret;
}
This question already has answers here:
Convert a string representation of a hex dump to a byte array using Java?
(25 answers)
Closed 8 years ago.
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?
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;
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.
I'm writing a little program in android and in it I've a list of byte values in a string variable. something like this :
String src = "255216173005050";
Now, what i need to do is to extract the byte values from the source string and store them in a byte variables. (in above source string, i'll have 5 bytes to store)
For doing this i could successfully read source string and separate the byte values by 3 characters. (255, 216, 173, 005, 050)
The problem is that i failed to convert these strings to their byte values.
it is what I've already done :
String str = "255";
byte b = (byte) Integer.parseInt(str);
By running this, b will be -60 !
Is there
Please help me !
When you write
byte b = (byte) Integer.parseInt(str);
you will get a signed byte. If you look at your int that is discarded using something like
int i = Integer.parseInt(str);
System.out.println(i);
byte b = (byte) i;
you will probably see that i contains the value you want.
This should work. Then just access various indices of the byte array to get the individual pieces. If your text is an abnormal character set - then pass the character set into the getBytes() method.
byte[] bytes = src.getBytes();
Don't use parseInt when you want a byte; instead try Byte.parseByte. Also note that bytes have a range of -128 to 127 (inclusive).
I have got the String MacAddress, which i need to convert in to a byte array. Java wouldn't let me do a direct conversion throwing a numberformat exception. This is what I'm doing right now
clientMac[0] = (byte)Integer.parseInt(strCameraMacId.substring(0, 2));
I tried doing it step by step
String mc = strCameraMacId.substring(0,2);
int test = Integer.parseInt(mc);
clientMac[0] = (byte) test;
But the String mc consists of a value "08" and after doing the int to byte converion im losing the zero.
the mac address im trying to convert is "08-00-23-91-06-48" and I might end up losing all the zeros. will I? and has anyone got an idea regarding how to approach this issue?
Thanks a lot
You are not losing the '0'. Because a byte is not a string, and 8 and 08 are the same.
But more important is this mistake in your code:
You're using the parseInt method. This parses your addresses as decimal integers. This won't work, because MAC addresses, when split the way you show them are usually HEX digits. You can come across 'A8' instead of '08' for example.
You need to use a different method:
Integer.parseInt(String s, int radix)
Pass the radix as 16 and you should be good.
The zero is going to be implied in the byte value. Remember that 0x08 == 8. You should be able to convert your to an array of 6 bytes. Youre approach is fine, just remember that if you are going to convert this back to a string, that you need to let Java know that you want to pad each number back to 2 chars. That will put your implied zeros back in place.
The IPAddress Java library will do this for you and will handle lots of different MAC address string formats, like aa:bb:cc:dd:ee:ff, aa-bb-cc-dd-ee-ff, aabb.ccdd.eeff, and so on. Disclosure: I am the project manager for that library.
Here is how to get a byte array:
String str = "aa:bb:cc:dd:ee:ff";
MACAddressString addrString = new MACAddressString(str);
try {
MACAddress addr = addrString.toAddress();
byte bytes[] = addr.getBytes();//get the byte array
//now convert to positive integers for printing
List<Integer> forPrinting = IntStream.range(0, bytes.length).map(index -> 0xff & bytes[index]).boxed().collect(Collectors.toList());
System.out.println("bytes for " + addr + " are " + forPrinting);
} catch(AddressStringException e) {
//e.getMessage provides validation issue
}
The output is:
bytes for aa:bb:cc:dd:ee:ff are [170, 187, 204, 221, 238, 255]
I'm working with java.
I have a byte array (8 bits in each position of the array) and what I need to do is to put together 2 of the values of the array and get a value.
I'll try to explain myself better; I'm extracting audio data from a audio file. This data is stored in a byte array. Each audio sample has a size of 16 bits. If the array is:
byte[] audioData;
What I need is to get 1 value from samples audioData[0] and audioData[1] in order to get 1 audio sample.
Can anyone explain me how to do this?
Thanks in advance.
I'm not a Java developer so this could be completely off-base, but have you considered using a ByteBuffer?
Assume the LSB is at data[0]
int val;
val = (((int)data[0]) & 0x00FF) | ((int)data[1]<<8);
As suggested before, Java has classes to help you with this. You can wrap your array with a ByteBuffer and then get an IntBuffer view of it.
ByteBuffer bb = ByteBuffer.wrap(audioData);
// optional: bb.order(ByteOrder.BIG_ENDIAN) or bb.order(ByteOrder.LITTLE_ENDIAN)
IntBuffer ib = bb.asIntBuffer();
int firstInt = ib.get(0);
ByteInputStream b = new ByteInputStream(audioData);
DataInputStream data = new DataInputStream(b);
short value = data.readShort();
The advantage of the above code is that you can keep reading the rest of 'data' in the same way.
A simpler solution for just two values might be:
short value = (short) ((audioData[0]<<8) | (audioData[1] & 0xff));
This simple solution extracts two bytes, and pieces them together with the first byte being the higher order bits and the second byte the lower order bits (this is known as Big-Endian; if your byte array contained Little-Endian data, you would shift the second byte over instead for 16-bit numbers; for Little-Endian 32-bit numbers, you would have to reverse the order of all 4 bytes, because Java's integers follow Big-Endian ordering).
easier way in Java to parse an array of bytes to bits is JBBP usage
class Parsed { #Bin(type = BinType.BIT_ARRAY) byte [] bits;}
final Parsed parsed = JBBPParser.prepare("bit:1 [_] bits;").parse(theByteArray).mapTo(Parsed.class);
the code will place parsed bits of each byte as 8 bytes in the bits array of the Parsed class instance
You can convert to a short (2 bytes) by logical or-ing the two bytes together:
short value = ((short) audioData[0]) | ((short) audioData[1] << 8);
I suggest you take a look at Preon. In Preon, you would be able to say something like this:
class Sample {
#BoundNumber(size="16") // Size of the sample in bits
int value;
}
class AudioFile {
#BoundList(size="...") // Number of samples
Sample[] samples;
}
byte[] buffer = ...;
Codec<AudioFile> codec = Codecs.create(AudioFile.class);
AudioFile audioFile = codec.decode(buffer);
You can do it like this, no libraries or external classes.
byte myByte = (byte) -128;
for(int i = 0 ; i < 8 ; i++) {
boolean val = (myByte & 256) > 0;
myByte = (byte) (myByte << 1);
System.out.print(val ? 1 : 0);
}
System.out.println();
byte myByte = 0x5B;
boolean bits = new boolean[8];
for(int i = 0 ; i < 8 ; i++)
bit[i] = (myByte%2 == 1);
The results is an array of zeros and ones where 1=TRUE and 0=FALSE :)