gpt4 book ai didi

C - 是否有更有效的方法将无符号字符数组的 "convert"项转换为 32 位整数值? (共享内存?)

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:54 24 4
gpt4 key购买 nike

最近我开始学习 C/C++,目前正在研究低级编程。我发现“union ”非常有趣,因为我以前从未见过这样的行为,可以用我学过的任何语言直接共享内存。现在我想知道是否有可能通过使用类似 Union 的东西或通过以某种方式将整数指向数组的特定索引以获得与下面相同的结果来提高这个简单例程的性能.

// An Union struct which holds a 32bit integer where every of the 4 bytes can be accessed.
typedef union
{
struct
{
unsigned char BYTE1;
unsigned char BYTE2;
unsigned char BYTE3;
unsigned char BYTE4;
} BYTES;
unsigned long VALUE;
} UnionDWORD;

// An array of unsigned chars - representing memory
unsigned char memory[1024]; // reserving 1024 bytes of memory

// Here is where I'm wondering if the "putting together" of the 4 bytes can be improved. (Maybe a pointer to the array?)
// Return 4bytes from memory at the position "pos"
unsigned long getDWordFromMemory(unsigned long pos)
{
// Making use of the Union struct to put the 4 bytes together
UnionDWORD result;
result.BYTES.BYTE4 = memory[pos];
result.BYTES.BYTE3 = memory[pos+1];
result.BYTES.BYTE2 = memory[pos+2];
result.BYTES.BYTE1 = memory[pos+3];

return result.VALUE;
}

非常感谢,我真的很抱歉我的英语不好。不幸的是,它不是我的母语。

最佳答案

当你拿着锤子时,一切看起来都像钉子。

假设使用 C++,这是一种更正确的方法来做可能是个坏主意:

unsigned long getDWordFromMemory(size_t pos)
{
unsigned char* mem = &memory[pos];
return *reinterpret_cast<unsigned long*>(mem);
}

如前所述,上面的内容存在对齐问题(您需要确保 pos 是 4 的倍数,因为 memory[0] 将正确对齐)。如果这是一个问题,那么你应该只使用这个方法:

unsigned long getDWordFromMemory(size_t pos)
{
unsigned long value;
memcpy(&value, &memory[pos], sizeof(value));
return value;
}

union 可能很有用,但它通常只是为了将不相交的信息打包到更小的内存中。

关于C - 是否有更有效的方法将无符号字符数组的 "convert"项转换为 32 位整数值? (共享内存?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43552969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com