簡體   English   中英

memcpy 是將浮點數裝入 uint32 的標准方法嗎?

[英]Is memcpy the standard way to pack float into uint32?

以下是將浮點數裝入 uint32 的最佳方法嗎? 這可能是一個快速而簡單的是,但我想確保沒有更好的方法,或者在進程之間交換值不會引入奇怪的皺紋。

在我的情況下,“最好”是它永遠不會在兼容的 C++ 編譯器上中斷(給定靜態斷言),可以在同一台計算機上的兩個進程之間打包和解包,並且與將 uint32 復制到另一個進程一樣快uint32。

流程一:

static_assert(sizeof(float) == sizeof(uint32) && alignof(float) == alignof(uint32), "no");
...

float f = 0.5f;
uint32 buffer[128];

memcpy(buffer + 41, &f, sizeof(uint32)); // packing

工藝乙:

uint32 * buffer = thisUint32Is_ReadFromProcessA(); // reads "buffer" from process A
...

memcpy(&f, buffer + 41, sizeof(uint32)); // unpacking

assert(f == 0.5f);

是的,這是進行類型雙關的標准方法。 Cppreferences 在memcpy上的頁面甚至包括一個示例,展示了如何使用它來將double重新解釋為int64_t

 #include <iostream> #include <cstdint> #include <cstring> int main() { // simple usage char source[] = "once upon a midnight dreary...", dest[4]; std::memcpy(dest, source, sizeof dest); for (char c : dest) std::cout << c << '\\n'; // reinterpreting double d = 0.1; // std::int64_t n = *reinterpret_cast<std::int64_t*>(&d); // aliasing violation std::int64_t n; std::memcpy(&n, &d, sizeof d); // OK std::cout << std::hexfloat << d << " is " << std::hex << n << " as an std::int64_t\\n"; }

輸出

o n c e 0x1.999999999999ap-4 is 3fb999999999999a as an std::int64_t

只要斷言通過(您正在寫入和讀取正確的字節數),那么操作就是安全的。 您不能將 64 位對象打包到 32 位對象中,但是您可以將一個 32 位對象打包到另一個 32 位對象中,只要它們是可 簡單復制的

或這個:

union TheUnion {
    uint32 theInt;
    float theFloat;
};

TheUnion converter;

converter.theFloat = myFloatValue;
uint32 myIntRep = converter.theInt;

我不知道這是否更好,但這是一種不同的看待它的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM