This question already has answers here:
Java code To convert byte to Hexadecimal
(23 answers)
Closed 9 years ago.
i m new to java. i want to convert a byte array of decimal value to hexadecimal string.
my input byte array is [0, 0, 0, 0, 0, 0, 1, -28]. i m getting 00000000000001e4 instead of 0000001e4. plz help me to solve this problem
public static String ConvetToHex(byte[] decValue)
{
String value = "";
for(int i = 0;i<decValue.length;i++)
{
value = value+ Integer.toString((decValue[i] & 0xff) + 0x100, 16).substring(1);
}
return value;
}
It looks correct to me. Eight bytes should turn into 16 hex characters. You can use
return new BigInteger(1, decValue).toString(16);
but it will produce the same output.
Related
This question already has answers here:
How to convert a Binary String to a base 10 integer in Java
(12 answers)
Closed 6 years ago.
I have attempted convert from 10000101 to -123 by code
byte sum = (byte) (Integer.valueOf(10000101, 2) & 0xffff) ";
now I don't know how to convert back from -123 to 10000101.
Any suggestions about using java API to do conversion?
Expanding a bit the David Wallace comment, you can do it with this code:
String fromByteToString = String.format("%8s", Integer.toBinaryString(sum & 0xFF)).replace(' ', '0');
System.out.println(fromByteToString);
with sum & 0xFF you do the bitwise AND operation:
-123 = 11111111111111111111111110000101
0xFF = 00000000000000000000000011111111
res. = 00000000000000000000000010000101
Note that the replace(' ', '0') is not a must in this case because the binary result string starts (10000101) with 1.
I need to write in a 8x8 matrix the binary values of 8 hexadecimal numbers (one for row). Those numbers will be at the most 8 bits long. I wrote the following code to convert from hexadecimal to binary:
private String hexToBin (String hex){
int i = Integer.parseInt(hex, 16);
String bin = Integer.toBinaryString(i);
return bin;
}
But I have the problem that values below 0x80 don't need 8 bits to be represented in binary. My question is: is there a function to convert to binary in an 8-bit format (filling the left positions with zeros)? Thanks a lot
My question is: is there a function to convert to binary in an 8-bit format (filling the left positions with zeros)?
No, there isn't. You have to write it yourself.
Here's one simple way. If you know the input is always a single byte, then you could add 256 to the number before calling toBinaryString. That way, the string will be guaranteed to be 9 characters long, and then you can just shave off the first character using substring:
String bin = Integer.toBinaryString(256 + i).substring(1);
Hint: use string concatenation to add the appropriate number of zeros in the appropriate place.
For example:
public String hexToBin(String hex) throws NumberFormatException {
String bin = Integer.toBinaryString(Integer.parseInt(hex, 16));
int len = bin.length();
return len == 8 ? bin : "00000000".substring(len - 8) + bin;
}
(Warning: untested ...)
I've concatenated this way. Thanks!
private String hexToBin (String hex){
int i = Integer.parseInt(hex, 16);
String bin = Integer.toBinaryString(i);
while (bin.length()<8){
bin="0"+bin;
}
return bin;
}
This question already has answers here:
java: convert binary string to int
(4 answers)
Closed 6 years ago.
there is a string fill with 0 and 1,like String s = "10000000", which length is 8.And how can i transform it to a byte.such as "10000000"===>-128.
I try to use Byte.parseByte(s, 2),but get the error "Value out of range. Value:"10000000" Radix:2".So,how can i solve it.
You need to parse it as an Integer and then cast it to byte:
...
String s = "10000000";
int val = Integer.parseInt(s, 2);
byte b = (byte) val;
System.err.println(b);
...
Output:
-128
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.
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.