[英]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
類型,那么你需要使用4
和12
作為你的第二和第三個值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.