这一步实际上已经完成了,因为我们已经有了包含4个字节的数组。 3. 使用Java的ByteBuffer或位操作将字节数组转换为int类型 方法一:使用ByteBuffer java import java.nio.ByteBuffer; public class ByteToIntConverter { public static int byteArrayToInt(byte[] bytes) { ByteBuffer buffer = ByteBuffer.wrap(bytes)...
}privatestaticinttoInt(byte[] bytes){intresult=0;for(inti=0; i <4; i++) { result <<=8; result |= bytes[i] &0xFF; }returnresult; } } 输出结果: cafebabe 说明这里的toInt方法是正确的。 参考文档 《java int 4个字节_将4个字节转换为int》...
/** * int转字节数组 大端模式 */ public static byte[] intToByteArrayBigEndian(int x) { byte[] bytes = new byte[4]; bytes[0] = (byte) (x >> 24); bytes[1] = (byte) (x >> 16); bytes[2] = (byte) (x >> 8); bytes[3] = (byte) x; return bytes; } /** * int转...
4字节数组转int类型 小端模式 /*** 数组转int类型 * *@paramsrc *@return*/publicstaticintbytesToInt(byte[] src) {intoffset = 0;intvalue; value= (int) ((src[offset] & 0xFF)| ((src[offset + 1] & 0xFF) << 8)| ((src[offset + 2] & 0xFF) << 16)| ((src[offset + 3] & ...
和bytesToInt()配套使用 * @param value * 要转换的int值 * @return byte数组 */ public static byte[] intToBytes( int value ) { byte[] src = new byte[4]; src[3] = (byte) ((value>>24) & 0xFF); src[2] = (byte) ((value>>16) & 0xFF); src[1] = (byte) ((value>>8)...
byte[] byteArray = new byte[]{1, 2, 3, 4};:创建一个包含四个字节的数组。 int integerValue = convertBytesToIntBigEndian(byteArray);:调用convertBytesToIntBigEndian方法,将字节数组转换为int。 convertBytesToIntBigEndian方法: int result = 0;:初始化结果变量。
* byte[]转int * @param bytes * @return */ public static int byteArrayToInt(byte[] bytes) { int value = 0; // 由高位到低位 for (int i = 0; i < 4; i++) { int shift = (4 - 1 - i) * 8; value += (bytes[i] & 0x000000FF) << shift;// 往高位游 ...
int a = -64; System.out.println("-64="+Integer.toBinaryString(-64)); byte[] bytes = CommonUtils.int2bytes(a); for(int i = 0 ; i<4 ; i++){ System.out.println(bytes[i]); } a = CommonUtils.bytes2int(bytes); System.out.println(a); ...
后来,闲着无聊,如果一个byte数组超过4位后,怎么办?当然返回一个int数组就行啦,反正4位byte转换成1个int,看着办就行。 public int[] bytesToInts(byte[] bytes){ int bytesLength=bytes.length; int[] ints=new int[bytesLength%4==0? bytesLength/4:bytesLength/4+1]; ...
}/*** 将一个4byte的数组转换成32位的int * *@parambuf * bytes buffer *@parambyte[]中开始转换的位置 *@returnconvert result*/publicstaticlongunsigned4BytesToInt(byte[] buf,intpos) {intfirstByte = 0;intsecondByte = 0;intthirdByte = 0;intfourthByte = 0;intindex =pos; ...