我在我的java代码中有这个方法,它返回给定int的字节数组:
private static byte[] intToBytes(int paramInt)
{
byte[] arrayOfByte = new byte[4];
ByteBuffer localByteBuffer = ByteBuffer.allocate(4);
localByteBuffer.putInt(paramInt);
for (int i = 0; i < 4; i++)
arrayOfByte[(3 - i)] = localByteBuffer.array()[i];
return arrayOfByte;
}
有人能给我一些提示吗?我怎样才能把这个方法转换成C++?
发布于 2011-04-08 02:20:23
使用std::vector<unsigned char>
#include <vector>
using namespace std;
vector<unsigned char> intToBytes(int paramInt)
{
vector<unsigned char> arrayOfByte(4);
for (int i = 0; i < 4; i++)
arrayOfByte[3 - i] = (paramInt >> (i * 8));
return arrayOfByte;
}
发布于 2011-04-08 02:07:32
你不需要一个完整的函数;一个简单的类型转换就足够了:
int x;
static_cast<char*>(static_cast<void*>(&x));
C++中的任何对象都可以重新解释为字节数组。如果您希望将字节实际复制到单独的数组中,则可以使用std::copy
int x;
char bytes[sizeof x];
std::copy(static_cast<const char*>(static_cast<const void*>(&x)),
static_cast<const char*>(static_cast<const void*>(&x)) + sizeof x,
bytes);
这两种方法都没有考虑字节顺序,但是由于您可以将int
重新解释为字节数组,因此自己执行任何必要的修改都很容易。
发布于 2011-04-08 02:09:13
您可以通过and和移位操作获得单个字节:
byte1 = nint & 0x000000ff
byte2 = (nint & 0x0000ff00) >> 8
byte3 = (nint & 0x00ff0000) >> 16
byte4 = (nint & 0xff000000) >> 24
https://stackoverflow.com/questions/5585532
复制相似问题