本文介紹了將 32 位無符號整數(大端)轉換為 long 并返回的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個 byte[4] 包含一個 32 位無符號整數(大端序),我需要將它轉換為 long(因為 int 不能保存無符號數).
I have a byte[4] which contains a 32-bit unsigned integer (in big endian order) and I need to convert it to long (as int can't hold an unsigned number).
另外,我該怎么做,反之亦然(即從包含 32 位無符號整數的 long 到 byte[4])?
Also, how do I do it vice-versa (i.e. from long that contains a 32-bit unsigned integer to byte[4])?
推薦答案
聽起來像是 ByteBuffer.
有點像
public static void main(String[] args) {
byte[] payload = toArray(-1991249);
int number = fromArray(payload);
System.out.println(number);
}
public static int fromArray(byte[] payload){
ByteBuffer buffer = ByteBuffer.wrap(payload);
buffer.order(ByteOrder.BIG_ENDIAN);
return buffer.getInt();
}
public static byte[] toArray(int value){
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putInt(value);
buffer.flip();
return buffer.array();
}
這篇關于將 32 位無符號整數(大端)轉換為 long 并返回的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!