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
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;