java binary byte bit

Convierta Byte a binario en Java



binary bit (3)

Estoy tratando de convertir un valor de byte a binario para la transferencia de datos. Básicamente, estoy enviando un valor como "AC" en binario ("10101100") en una matriz de bytes donde "10101100" es un byte único. Quiero poder recibir este byte y convertirlo nuevamente en "10101100". Por el momento no tengo éxito en absoluto, realmente no sé por dónde empezar. Cualquier ayuda sería genial.

editar : disculpa por toda la confusión. No me di cuenta de que olvidé agregar detalles específicos.

Básicamente, necesito usar una matriz de bytes para enviar valores binarios a través de una conexión de socket. Puedo hacer eso pero no sé cómo convertir los valores y hacerlos aparecer correctamente. Aquí hay un ejemplo:

Necesito enviar los valores hexadecimales ACDE48 y ser capaz de interpretarlos de nuevo. De acuerdo con la documentación, debo convertirlo a binario de la siguiente manera: byte [] b = {10101100,11011110,01001000}, donde cada lugar en la matriz puede contener 2 valores. Luego necesito volver a convertir estos valores después de que se envíen y reciban. No estoy seguro de cómo hacerlo.


Para convertir hexadecimal en binario, puede usar BigInteger para simplificar su código.

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

Los bytes se envían como binarios sin traducción. De hecho, es el único tipo que no requiere alguna forma de codificación. Como tal, no hay nada que hacer.

Para escribir un byte en binario

OutputStream out = ... out.write(byteValue); InputStream in = ... int n = in.read(); if (n >= 0) { byte byteValue = (byte) n;


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

Hay algunas formas más simples de manejar esto también (se asume big endian).

Integer.parseInt(hex, 16); Integer.parseInt(binary, 2);

y

Integer.toHexString(byte).subString((Integer.SIZE - Byte.SIZE) / 4); Integer.toBinaryString(byte).substring(Integer.SIZE - Byte.SIZE);


La alternativa a la solución @ LINEMAN78s es:

public byte[] getByteByString(String byteString){ return new BigInteger(byteString, 2).toByteArray(); } public String getStringByByte(byte[] bytes){ StringBuilder ret = new StringBuilder(); if(bytes != null){ for (byte b : bytes) { ret.append(Integer.toBinaryString(b & 255 | 256).substring(1)); } } return ret.toString(); }