Questions tagged «type-punning»


15
C和C ++中的合并目的
我以前很舒服地使用过工会。今天,当我阅读这篇文章并得知此代码时,我感到震惊 union ARGB { uint32_t colour; struct componentsTag { uint8_t b; uint8_t g; uint8_t r; uint8_t a; } components; } pixel; pixel.colour = 0xff040201; // ARGB::colour is the active member from now on // somewhere down the line, without any edit to pixel if(pixel.components.a) // accessing the non-active member ARGB::components …
254 c++  c  unions  type-punning 

3
是否可以在Rust中编写Quake的快速InvSqrt()函数?
这只是为了满足我自己的好奇心。 是否有此实现: float InvSqrt (float x) { float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f - xhalf*x*x); return x; } 在Rust中?如果存在,则发布代码。 我尝试过但失败了。我不知道如何使用整数格式编码浮点数。这是我的尝试: fn main() { println!("Hello, world!"); println!("sqrt1: {}, ",sqrt2(100f64)); } fn sqrt1(x: f64) -> f64 { x.sqrt() } …

5
联合与类型搭配
我已经搜索了一段时间,但找不到明确的答案。 许多人说,使用union来进行pun-pun是不确定的,也是不好的做法。为什么是这样?考虑到您将原始信息写入的内存,它不会做任何未定义的事情,而不会改变它的任何原因(除非它超出了堆栈范围,但这不是联合问题) ,那将是不好的设计)。 人们引用了严格的别名规则,但是在我看来,这就像在说您不能执行,因为您无法执行。 如果不键入pun,联合的意义是什么?我在某处看到应该在不同的时间将相同的内存位置用于不同的信息,但是为什么不删除信息然后再使用呢? 总结一下: 为什么使用联合进行类型修剪是不好的? 如果不是这样,他们的目的是什么? 额外信息:我主要使用C ++,但想了解有关C和C的信息。特别是,我使用联合在浮点数和通过CAN总线发送的原始十六进制之间进行转换。
76 c++  c  unions  type-punning 

3
std :: bit_cast与std :: array
Timur Doumler 在他最近的演讲“现代C ++中的类型修剪”中说,由于不能从函数返回C样式的数组,std::bit_cast因此不能用于将a 强制float转换unsigned char[4]为a。我们应该使用std::memcpy或等到C ++ 23(或更高版本)后,类似的东西reinterpret_cast<unsigned char*>(&f)[i]才能很好地定义。 在C ++ 20中,我们可以在中std::array使用std::bit_cast, float f = /* some value */; auto bits = std::bit_cast<std::array<unsigned char, sizeof(float)>>(f); 而不是C样式的数组来获取float?的字节?
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.