大小端byte与int互转
java部分来自:https://blog.csdn.net/a22422931/article/details/64929815
/**
* 以大端模式将int转成byte[]
*/
public static byte[] intToBytesBig(int value) {
byte[] src = new byte[4];
src[0] = (byte) ((value >> 24) & 0xFF);
src[1] = (byte) ((value >> 16) & 0xFF);
src[2] = (byte) ((value >> 8) & 0xFF);
src[3] = (byte) (value & 0xFF);
return src;
}
/**
* 以小端模式将int转成byte[]
*
* @param value
* @return
*/
public static byte[] intToBytesLittle(int value) {
byte[] src = new byte[4];
src[3] = (byte) ((value >> 24) & 0xFF);
src[2] = (byte) ((value >> 16) & 0xFF);
src[1] = (byte) ((value >> 8) & 0xFF);
src[0] = (byte) (value & 0xFF);
return src;
}
/**
* 以大端模式将byte[]转成int
*/
public static int bytesToIntBig(byte[] src, int offset) {
int value;
value = (int) (((src[offset] & 0xFF) << 24)
| ((src[offset + 1] & 0xFF) << 16)
| ((src[offset + 2] & 0xFF) << 8)
| (src[offset + 3] & 0xFF));
return value;
}
/**
* 以小端模式将byte[]转成int
*/
public static int bytesToIntLittle(byte[] src, int offset) {
int value;
value = (int) ((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24));
return value;
}
本段java来自同事:
public static int bytesToInt(byte[] src) {
ByteBuffer buffer = ByteBuffer.wrap(src);
// buffer.order(ByteOrder.nativeOrder());//获取系统
// buffer.order(ByteOrder.BIG_ENDIAN);//大端
buffer.order(ByteOrder.LITTLE_ENDIAN);//小端
return buffer.getInt();
}
以下为小端go代码:
// Int2Byte 将int写入指定长度的[]byte
func Int2Byte(data, len int) (ret []byte) {
ret = make([]byte, len)
var tmp int = 0xff
var index uint = 0
for index = 0; index < uint(len); index++ {
ret[index] = byte((tmp << (index * 8) & data) >> (index * 8))
}
return ret
}
// Byte2Int 从[]byte中读取长度
func Byte2Int(data []byte) int {
var ret int = 0
var len int = len(data)
var i uint = 0
for i = 0; i < uint(len); i++ {
ret = ret | (int(data[i]) << (i * 8))
}
return ret
}
以下go代码来自:https://www.zhihu.com/question/327537211/answer/703010418
package main
import (
"encoding/binary"
"fmt"
)
func main() {
bytes := []byte{0x78, 0x56, 0x34, 0x12}
fmt.Printf("0x%x\n", binary.LittleEndian.Uint32(bytes))
fmt.Printf("0x%x\n", binary.BigEndian.Uint32(bytes))
}