How to convert byte to binary in java? [duplicate] - java

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.

Related

What does (b & 0xff) mean? [duplicate]

This question already has answers here:
What does value & 0xff do in Java?
(4 answers)
Closed 9 years ago.
With Java, I am converting a String value to a hash using SHA1 on a MessageDigest instance. I am at the point where I have created a hash object:
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] hash = md.digest(password.getBytes("UTF-8"));
The part I do not understand is what b & 0xff means in the following code:
StringBuilder sb = new StringBuilder(2*hash.length);
for(byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
I know that %02x means to specify a format where there are two characters using hexadecimal, but I've no idea what the second parameter is, what it does to each byte or what it means. A simple explanation would be great! :-)
That's the bitwise AND operator. b & 0xff gets the last byte of b. Since b is already a byte, I don't see any point to this: the result of the String.format is the same.

How to convert short array to byte array? [duplicate]

This question already has answers here:
how to convert short array to byte array
(3 answers)
Closed 9 years ago.
I am working with audio, I saved audio data on short array. I want to convert it to a byte array to store the wav file. I don't know convert short[] to byte[]. Can you help me.
Thank you very much.
short is 16 bit type and byte is 8 bit type . So from a n length short array you will get a 2n length byte array.
The Basics
before converting an array thing about converting a single short to byte. so as per above line you will create 2 byte from a single short.
The principle will be store first 8 bits two a byte and store second 8 bits to another short. The code will be like this
byte b1, b2;
short s;
b1 = s & 0xff;
b2 = (s >> 8) & 0xff;
Now Array
use the above principal for array now. say the array size of short is n. let the short is s
byte result[2*n];
for(int i = 0; i<2*n ; i=i+2){
b[i] = s[i>>1] & 0xff;
b[i+1] = (s[i>>1 | 1] >> 8) & 0xff;
}
Using ByteBuffer class
you can also convert short array to bytearray using ByteBuffer class.
ByteBuffer byteBuf = ByteBuffer.allocate(2*n);
for(int i = 0; i<n ; i++) {
byteBuf.putShort(buffer[i]);
}
The only way is to create a byte array of the same size as the short array and copy the short array elements

Java: Problems converting char to int [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java char array to int
I have the following code, where stackCells is an ArrayList object:
int[] stackCell = {0, 0};
if (!stackCells.isEmpty()) {
String stackCellString = stackCells.get(0);
stackCell[0] = stackCellString.charAt(0);
stackCell[1] = stackCellString.charAt(1);
}
So the problem I am encountering is that stackCell is not interpreting the character as an int. For example, the value of stackCellString should be "88". However, when I use chartAt(0) and charAt(1), I get an int value of 56. If I use those same calls inside a System.out.println(stackCellString.charAt(0) + stackCellString.charAt(1)) command, I get the correct result (i.e. "88").
It's interpreting the character as an int in the following way:
56 is the ASCII code for the character '8'.
If you want to grab the numeric digits from the string, you will need to use something like Integer.parseInt() as one of the comments mentioned.
A more efficient solution might be to do some math based on the ASCII code. If you know all of the characters are decimal digits, you could do (code - 48) to get the digit (where code is the ASCII code). For instance, (56 - 48) = 8, which is what you want here.
56 is the ASCII code of the digit 8. To get what you want, you could do this:
stackCell[0] = stackCellString.charAt(0) - '0';
stackCell[1] = stackCellString.charAt(1) - '0';
String stackCellString="88";
stackCell[0] = stackCellString.charAt(0);
stackCell[1] = stackCellString.charAt(1);
System.out.println(stackCell[0]);
System.out.println(stackCell[1]);
System.out.println(stackCell[0]+stackCell[1]);
System.out.println(stackCellString.charAt(0) + stackCellString.charAt(1));
output:
56
56
112
112
You are not returning the charAt as its character representation.
If you want it to return "88" you need to do this:
stackCellString.subString(0,1) + stackCellString.subString(1,2);
Another work around is this:
"" + stackCellString.charAt(0) + stackCellString.charAt(1);

converting byte array of decimal value to hexadecimal string in java [duplicate]

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.

Java - byte array from string [duplicate]

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.

Categories

Resources