我正在使用RakNet进行网络连接,我需要传输浮点值.问题是,我只能发送单个字节.因为float由4个字节组成,所以我认为必须将浮动分解为这四个字节并发送它们.在那之后,我想再次将它们组合成一个浮子.
我怎么做?
memcpy原始float值到适当大小的unsigned chars 数组
float f = ...;
unsigned char c[sizeof f];
memcpy(c, &f, sizeof f);
// use `c[i]` to access the bytes
Run Code Online (Sandbox Code Playgroud)将原始指针重新解释为unsigned chars 的数组reinterpret_cast
float f = ...;
unsigned char *c = reinterpret_cast<unsigned char *>(&f);
// use `c[i]` to access the bytes
Run Code Online (Sandbox Code Playgroud)使用联合执行相同的重新解释
union FC {
float f;
unsigned char c[sizeof FC::f];
};
float f = ...;
FC u = { f };
// use `u.c[i]` to access the bytes
Run Code Online (Sandbox Code Playgroud)只要牢记一些额外的细节:最后一种方法(使用union)现在是用C法律,但仍然是在C++中正式违法-你读不准用C工会的"不活跃"的成员++.观察little-big-bigian平台上的字节顺序.如果您使用第二种方法,也将接收者重新解释float为unsigned chars 的数组,而不是相反,以避免对齐问题.