网上搜了很多内容,没有找到直接转换函数,有一个转换代码需要将byte数组转换为字符数组,以字符数组为参数转换为int整数,多了一层转换。好不容易找到一个直接转换函数,记录下来,其中 bytes[0]存储低位,bytes[3]存储高位字节。
//int转byte
void intToByte(int i,byte *bytes,int size = 4)
{//byte[] bytes = new byte[4];
memset(bytes,0,sizeof(byte) * size);
bytes[0] = (byte) (0xff & i);
bytes[1] = (byte) ((0xff00 & i) >> 8);
bytes[2] = (byte) ((0xff0000 & i) >> 16);
bytes[3] = (byte) ((0xff000000 & i) >> 24);
return ;
}
//byte转int
int bytesToInt(byte* bytes,int size = 4)
{
int addr = bytes[0] & 0xFF;
addr |= ((bytes[1] << 8) & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 24) & 0xFF000000);
return addr;
}
=======================
2014.06.09改进
//byte转int
int bytesToInt(byte* bytes,int size = 4)
{
int addr = bytes[0];
addr |= (bytes[1] << 8);
addr |= (bytes[2] << 16);
addr |= (bytes[3] << 24);
return addr;
}