C++: byte数组和int整数的相互转化

网上搜了很多内容,没有找到直接转换函数,有一个转换代码需要将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;

 }

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值