Getting int32_t or int64_t value from char array

I need to perform an operation requiring me to get one int32_t value and 2 int64_t values โ€‹โ€‹from a char array

the first 4 bytes of the char array contain the value int32, the next 8 bytes contain the first value int64_t, the next 8 bytes contain the second. I canโ€™t figure out how to get to these values. I tried:

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]; 

I just grab onto a straw. Any help appreciated

+6
source share
4 answers

Quick and dirty solution:

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

Please note that this may result in improper memory access. So this may not always work.


A more robust solution that does not violate strict anti-aliasing and will not have alignment problems:

 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)); 
+4
source

try it

 typedef struct { int32_t firstValue; int64_t secondValue; int64_t thirdValue; } hd; hd* p = reinterpret_cast<hd*>(charArray); 

now you can access the values, for example. n-> firstValue

EDIT: make sure the structure is packed on byte boundaries, for example. with Visual Studio you write #pragma pack(1) before struct

+1
source

To avoid any alignment problems, the ideal solution is to copy bytes from the buffer to the targets. You can use some useful utilities for this:

 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; } 

Then your problem is pretty simple:

 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); 
+1
source

if charArray is 1 char byte then you need to use 4 and 12 for your 2nd and 3rd values

0
source

Source: https://habr.com/ru/post/921452/


All Articles