在Java中将字节转换为二进制

我试图将字节值转换为二进制数据传输。 基本上,我在二进制(“10101100”)中以字节数组的forms发送类似“AC”的值,其中“10101100”是单字节。 我希望能够接收此字节并将其转换回“10101100”。 截至目前,我根本没有成功,也不知道从哪里开始。 任何帮助都会很棒。

编辑 :抱歉所有的困惑我没有意识到我忘了添加具体的细节。

基本上我需要使用字节数组通过套接字连接发送二进制值。 我可以这样做,但我不知道如何转换值并使它们正确显示。 这是一个例子:

我需要发送hex值ACDE48并能够将其解释回来。 根据文档,我必须通过以下方式将其转换为二进制:byte [] b = {10101100,11011110,01001000},其中数组中的每个位置可以包含2个值。 然后,我需要在发送和接收后将这些值转换回来。 我不知道该怎么做。

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

还有一些更简单的方法来处理这个问题(假设是大端)。

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

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

要将hex转换为二进制,可以使用BigInteger来简化代码。

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

字节以二进制forms发送而不进行转换。 事实上它是唯一不需要某种forms编码的类型。 因此,无所事事。

用二进制写一个字节

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

@ LINEMAN78s解决方案的替代方案是:

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