คำถามติดแท็ก 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 …
254 c++  c  unions  type-punning 

3
เป็นไปได้ไหมที่จะเขียนฟังก์ชัน InvSqrt () ของ Quake ใน Rust?
นี่เป็นเพียงเพื่อสนองความอยากรู้อยากเห็นของฉันเอง มีการดำเนินการตามนี้หรือไม่: 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; } ในสนิม ถ้ามีอยู่โพสต์รหัส ฉันลองแล้วล้มเหลว ฉันไม่ทราบวิธีเข้ารหัสตัวเลขทศนิยมโดยใช้รูปแบบจำนวนเต็ม นี่คือความพยายามของฉัน: fn main() { println!("Hello, world!"); println!("sqrt1: {}, ",sqrt2(100f64)); } fn sqrt1(x: f64) -> f64 …

3
std :: bit_cast พร้อม std :: array
ในการพูดคุยล่าสุดของเขา“ชนิดเล่นสำนวนในปัจจุบัน c ++”มู Doumler กล่าวว่าstd::bit_castไม่สามารถนำมาใช้เพื่อบิตโยนfloatลงไปunsigned char[4]เพราะอาร์เรย์แบบ C ไม่สามารถกลับมาจากฟังก์ชั่น เราควรใช้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?
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.