4

データ転送のためにバイト値をバイナリに変換しようとしています。基本的には、「10101100」が1バイトのバイト配列で、「AC」のような値をバイナリ(「10101100」)で送信しています。このバイトを受け取って「10101100」に変換できるようにしたいのです。今のところ、私はまったく成功していません。どこから始めればよいのか本当にわかりません。どんな助けでも素晴らしいでしょう。

編集:特定の詳細を追加するのを忘れていたことに気付かなかったすべての混乱をお詫びします。

基本的に、ソケット接続を介してバイナリ値を送信するには、バイト配列を使用する必要があります。それはできますが、値を変換して正しく表示する方法がわかりません。次に例を示します。

16 進値 ACDE48 を送信し、それを解釈できるようにする必要があります。ドキュメントによると、次の方法でバイナリに変換する必要があります: byte [] b={10101100,11011110,01001000}。配列内の各場所は 2 つの値を保持できます。次に、これらの値を送受信した後に元に戻す必要があります。これを行う方法がわかりません。

4

3 に答える 3

17
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);
于 2012-07-17T19:16:08.670 に答える
2

16 進数を 2 進数に変換するには、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;
于 2012-07-17T19:04:03.433 に答える
1

@ 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();
}
于 2016-11-18T08:53:48.300 に答える