質問

8バイトの配列があり、対応する数値に変換したい。

e.g。

byte[] by = new byte[8];  // the byte array is stored in 'by'

// CONVERSION OPERATION
// return the numeric value

上記の変換操作を実行するメソッドが必要です。

役に立ちましたか?

解決

最初のバイトが最下位バイトであると仮定:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value += ((long) by[i] & 0xffL) << (8 * i);
}

最初のバイトが最も重要な場合、それは少し異なります:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value = (value << 8) + (by[i] & 0xff);
}

BigInteger でlongを置き換えます。 8バイト以上あります。

エラーを修正してくれたアーロン・ディグラに感謝します。

他のヒント

バッファ noreferrer "> java.nio パッケージで変換を実行します。

ここで、ソースの byte [] 配列の長さは8です。これは、 long 値に対応するサイズです。

まず、 byte [] 配列は ByteBuffer 、次に ByteBuffer.getLong メソッドを呼び出して、 long 値を取得します。

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();

System.out.println(l);

結果

4

コメントで ByteBuffer.getLong メソッドを指摘してくれたdfaに感謝します。


この状況では適用できないかもしれませんが、 Buffer の美しさは、複数の値を持つ配列を見ることです。

たとえば、8バイトの配列があり、2つの int 値として表示したい場合、 byte [] 配列を< として表示されるcode> ByteBuffer IntBuffer IntBuffer.get

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4});
IntBuffer ib = bb.asIntBuffer();
int i0 = ib.get(0);
int i1 = ib.get(1);

System.out.println(i0);
System.out.println(i1);

結果:

1
4

これが8バイトの数値の場合、次を試すことができます:

BigInteger n = new BigInteger(byteArray);

これがUTF-8文字バッファーの場合、次を試すことができます:

BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));

単純に、Googleが提供する guava libを使用または参照できます。これは、長い配列とバイト配列の間の変換に便利なメソッドを提供します。私のクライアントコード:

    long content = 212000607777l;
    byte[] numberByte = Longs.toByteArray(content);
    logger.info(Longs.fromByteArray(numberByte));

可変長バイトにBigIntegerを使用することもできます。必要に応じて、Long、Integer、Shortのいずれかに変換できます。

new BigInteger(bytes).intValue();

または極性を示す:

new BigInteger(1, bytes).intValue();

配列との間のすべてのプリミティブ型の完全なJavaコンバーターコード http://www.daniweb.com/code/snippet216874.html

配列内の各セルは、unsigned intとして扱われます:

private int unsignedIntFromByteArray(byte[] bytes) {
int res = 0;
if (bytes == null)
    return res;


for (int i=0;i<bytes.length;i++){
    res = res | ((bytes[i] & 0xff) << i*8);
}
return res;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top