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

时间:2023-03-08 20:07:57

原文链接:http://blog.****.net/puttytree/article/details/7825709

NumberUtil.h

//
// NumberUtil.h
// MinaCppClient
//
// Created by yang3wei on 7/22/13.
// Copyright (c) 2013 yang3wei. All rights reserved.
// #ifndef __MinaCppClient__NumberUtil__
#define __MinaCppClient__NumberUtil__ #include <string> /**
* htonl 表示 host to network long ,用于将主机 unsigned int 型数据转换成网络字节顺序;
* htons 表示 host to network short ,用于将主机 unsigned short 型数据转换成网络字节顺序;
* ntohl、ntohs 的功能分别与 htonl、htons 相反。
*/ /**
* byte 不是一种新类型,在 C++ 中 byte 被定义的是 unsigned char 类型;
* 但在 C# 里面 byte 被定义的是 unsigned int 类型
*/
typedef unsigned char byte; /**
* int 转 byte
* 方法无返回的优点:做内存管理清爽整洁
* 如果返回值为 int,float,long,double 等简单类型的话,直接返回即可
* 总的来说,这真心是一种很优秀的方法设计模式
*/
void int2bytes(int i, byte* bytes, int size = 4); // byte 转 int
int bytes2int(byte* bytes, int size = 4); #endif /* defined(__MinaCppClient__NumberUtil__) */

NumberUtil.cpp

//
// NumberUtil.cpp
// MinaCppClient
//
// Created by yang3wei on 7/22/13.
// Copyright (c) 2013 yang3wei. All rights reserved.
// #include "NumberUtil.h" void int2bytes(int i, byte* bytes, int size) {
// 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);
} int bytes2int(byte* bytes, int size) {
int iRetVal = bytes[0] & 0xFF;
iRetVal |= ((bytes[1] << 8) & 0xFF00);
iRetVal |= ((bytes[2] << 16) & 0xFF0000);
iRetVal |= ((bytes[3] << 24) & 0xFF000000);
return iRetVal;
}