2012-07-27 74 views
6

我需要执行的操作需要我从一个字符阵列得到一个int32_t值和2的int64_t值获取一个int32_t或从一个字符阵列的int64_t值

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

我只是抓着吸管。任何帮助表示赞赏

+0

'int32_t * firstArray = reinterpet_cast (charArray);'应该实际工作。不是吗? – Mysticial 2012-07-27 04:34:42

+0

是的,我实际上可以得到数组,但我如何获得第二个和第三个值?他们是64位。 – Miek 2012-07-27 04:36:32

回答

4

快速和肮脏的解决方案:

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)); 
+0

[Edsger Dijkstra算法不批准你的第一个解决方案。(http://www.catonmat.net/blog/wp-content/uploads/2008/11/edsger-dijkstra-quick-and-dirty.jpg) – 2012-07-27 04:41:47

+0

谢谢你非常喜欢,最好的方法应该适合我的需要,并且我现在看到它再次看到它。 – Miek 2012-07-27 04:46:23

+1

@Miek要知道,第一个解决方案不是由标准保证的 - 即使它可能会在所有现代的编译器与'的sizeof(int32_t)工作== 4'和'的sizeof(的int64_t)== 8' – Mysticial 2012-07-27 04:48:08

0

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

1

试试这个

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

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

现在您可以访问例如P-> firstValue

编辑:确保结构包装上字节边界例如使用Visual Studio你结构

+0

由于'struct'填充和对齐,这将不起作用。 – Mysticial 2012-07-27 04:38:35

+0

,然后将限定包设置为字节,例如的#pragma包(1) – 2012-07-27 04:41:04

+0

填充可以阻止这样做...你可以使用'的#pragma pack'指令,但是,是不是太轻便。 – dreamlax 2012-07-27 04:42:13

1

之前写#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); 
相关问题