繁体   English   中英

从char数组获取int32_t或int64_t值

[英]Getting a int32_t or a int64_t value from a char array

我需要执行的操作要求我从char数组中获取一个int32_t值和2个int64_t值

char数组的前4个字节包含int32值,接下来的8个字节包含第一个int64_t值,接下来的8个字节包含第二个字节。 我无法弄清楚如何获得这些价值观。 我试过了;

int32_t firstValue = (int32_t)charArray[0];
int64_t firstValue = (int64_t)charArray[1];
int64_t firstValue = (int64_t)charArray[3];

int32_t *firstArray = reinterpet_cast<int32_t*>(charArray);
int32_t num = firstArray[0]; 
int64_t *secondArray = reinterpet_cast<int64_t*>(charArray);
int64_t secondNum = secondArray[0];

我只是抓住稻草。 任何帮助赞赏

快速而肮脏的解决方

int32_t value1 = *(int32_t*)(charArray +  0);
int64_t value2 = *(int64_t*)(charArray +  4);
int64_t value3 = *(int64_t*)(charArray + 12);

请注意,这可能会导致未对齐的内存访问。 所以它可能并不总是有效。


更强大的解决方案,不违反严格别名,不会出现对齐问题:

int32_t value1;
int64_t value2;
int64_t value3;

memcpy(&value1,charArray +  0,sizeof(int32_t));
memcpy(&value2,charArray +  4,sizeof(int64_t));
memcpy(&value3,charArray + 12,sizeof(int64_t));

试试这个

typedef struct {
   int32_t firstValue;
   int64_t secondValue;
   int64_t thirdValue;
} hd;

hd* p = reinterpret_cast<hd*>(charArray);

现在您可以访问值,例如p-> firstValue

编辑:确保结构打包在字节边界上,例如使用Visual Studio在结构之前编写#pragma pack(1)

为了避免任何对齐问题,理想的解决方案是将缓冲区中的字节复制到目标对象中。 为此,您可以使用一些有用的实用程序:

typedef unsigned char const* byte_iterator;

template <typename T>
byte_iterator begin_bytes(T& x)
{
    return reinterpret_cast<byte_iterator>(&x);
}

template <typename T>
byte_iterator end_bytes(T& x)
{
    return reinterpret_cast<byte_iterator>(&x + 1);
}

template <typename T>
T safe_reinterpret_as(byte_iterator const it)
{
    T o;
    std::copy(it, it + sizeof(T), ::begin_bytes(o));
    return o;
}

那么你的问题很简单:

int32_t firstValue  = safe_reinterpret_as<int32_t>(charArray);
int64_t secondValue = safe_reinterpret_as<int64_t>(charArray + 4);
int64_t thirdValue  = safe_reinterpret_as<int64_t>(charArray + 12);

如果charArray是一个1字节的char类型,那么你需要使用412作为你的第二和第三个值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM