C++: byte和int的相互转化

来源:互联网 发布:调查报告的数据分析 编辑:程序博客网 时间:2024/05/17 03:14

byte不是一种新类型,在C++中byte被定义的是unsigned char类型;但在C#里面byte被定义的是unsigned int类型

//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;
 }