[英]How to convert byte array to hex string which it is using for convert it to long?
[英]convert int or long to byte hex array
將整數或長值轉換為字節緩沖區的最簡單方法是什么?
例:
輸入:325647187
輸出:{0x13,0x68,0xfb,0x53}
我已經嘗試過像這樣的ByteBuffer:
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putLong(325647187);
byte[] x=buffer.array();
for(int i=0;i<x.length;i++)
{
System.out.println(x[i]);
}
但我例外
Exception in thread "main" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Buffer.java:527)
at java.nio.HeapByteBuffer.putLong(HeapByteBuffer.java:423)
at MainApp.main(MainApp.java:11)
您分配了一個4字節的緩沖區,但是在調用putLong
,您試圖在其中放入8個字節。 因此,溢出。 調用ByteBuffer.allocate(8)
將阻止該異常。
或者,如果編碼的數字是整數(如您的代碼段所示),則足以分配4個字節並調用putInt()
。
您可以嘗試此方法,以實現更簡單的轉換方式:
所以您輸入325647187作為輸入,然后我們可以輸入如下內容
byte[] bytes = ByteBuffer.allocate(4).putInt(325647187).array();
for (byte b : bytes)
{
System.out.format("0x%x ", b);
}
對我來說,這(如果不是最多的話)是一種轉換為字節緩沖區的有效方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.