I am trying to convert a byte value to binary for data transfer. Basically, I am sending a value like "AC" in binary ("10101100") in a byte array where "10101100" is a single byte. I want to be able to receive this byte and convert it back into "10101100." As of now I have no success at all dont really know where to begin. Any help would be great.
edit: sorry for all the confusion I didnt realize that I forgot to add specific details.
Basically I need to use a byte array to send binary values over a socket connection. I can do that but I dont know how to convert the values and make them appear correctly. Here is an example:
I need to send the hex values ACDE48 and be able to interpret it back. According to documentation, I must convert it to binary in the following way: byte [] b={10101100,11011110,01001000}, where each place in the array can hold 2 values. I then need to convert these values back after they are sent and received. I am not sure how to go about doing this.
String toBinary( byte[] bytes )
{
StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
for( int i = 0; i < Byte.SIZE * bytes.length; i++ )
sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
return sb.toString();
}
byte[] fromBinary( String s )
{
int sLen = s.length();
byte[] toReturn = new byte[(sLen + Byte.SIZE - 1) / Byte.SIZE];
char c;
for( int i = 0; i < sLen; i++ )
if( (c = s.charAt(i)) == '1' )
toReturn[i / Byte.SIZE] = (byte) (toReturn[i / Byte.SIZE] | (0x80 >>> (i % Byte.SIZE)));
else if ( c != '0' )
throw new IllegalArgumentException();
return toReturn;
}
There are some simpler ways to handle this also (assumes big endian).
Integer.parseInt(hex, 16);
Integer.parseInt(binary, 2);
and
Integer.toHexString(byte).subString((Integer.SIZE - Byte.SIZE) / 4);
Integer.toBinaryString(byte).substring(Integer.SIZE - Byte.SIZE);
For converting hexidecimal into binary, you can use BigInteger to simplify your code.
public static void sendHex(OutputStream out, String hexString) throws IOException {
byte[] bytes = new BigInteger("0" + hexString, 16).toByteArray();
out.write(bytes, 1, bytes.length-1);
}
public static String readHex(InputStream in, int byteCount) throws IOException {
byte[] bytes = new byte[byteCount+1];
bytes[0] = 1;
new DataInputStream(in).readFully(bytes, 1, byteCount);
return new BigInteger(0, bytes).toString().substring(1);
}
Bytes are sent as binary without translation. It fact its the only type which doesn't require some form of encoding. As such there is nothing to do.
To write a byte in binary
OutputStream out = ...
out.write(byteValue);
InputStream in = ...
int n = in.read();
if (n >= 0) {
byte byteValue = (byte) n;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With