簡體   English   中英

在Java中將字節轉換為二進制

[英]Convert Byte to binary in Java

我試圖將字節值轉換為二進制數據傳輸。 基本上,我在字節數組中以二進制(“10101100”)發送類似“AC”的值,其中“10101100”是單字節。 我希望能夠接收此字節並將其轉換回“10101100”。 截至目前,我根本沒有成功,也不知道從哪里開始。 任何幫助都會很棒。

編輯 :抱歉所有的困惑我沒有意識到我忘了添加具體的細節。

基本上我需要使用字節數組通過套接字連接發送二進制值。 我可以這樣做,但我不知道如何轉換值並使它們正確顯示。 這是一個例子:

我需要發送十六進制值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);

要將十六進制轉換為二進制,可以使用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);
}

字節以二進制形式發送而不進行轉換。 事實上它是唯一不需要某種形式編碼的類型。 因此,無所事事。

用二進制寫一個字節

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM