What’s a proper way of type-punning a float to an int and vice-versa?

Forget casts. Use memcpy. float xhalf = 0.5f*x; uint32_t i; assert(sizeof(x) == sizeof(i)); std::memcpy(&i, &x, sizeof(i)); i = 0x5f375a86 – (i>>1); std::memcpy(&x, &i, sizeof(i)); x = x*(1.5f – xhalf*x*x); return x; The original code tries to initialize the int32_t by first accessing the float object through an int32_t pointer, which is where the rules are … Read more

Is it allowed to use unions for type punning, and if not, why?

To re-iterate, type-punning through unions is perfectly fine in C (but not in C++). In contrast, using pointer casts to do so violates C99 strict aliasing and is problematic because different types may have different alignment requirements and you could raise a SIGBUS if you do it wrong. With unions, this is never a problem. … Read more

What is the modern, correct way to do type punning in C++?

First of all, you assume that sizeof(long) == sizeof(int) == sizeof(float). This is not always true, and totally unspecified (platform dependent). Actually, this is true on my Windows using clang-cl and wrong on my Linux using the same 64-bit machine. Different compilers on the same OS/machine can give different results. A static assert is at … Read more

Fix for dereferencing type-punned pointer will break strict-aliasing

First off, let’s examine why you get the aliasing violation warnings. Aliasing rules simply say that you can only access an object through its own type, its signed / unsigned variant type, or through a character type (char, signed char, unsigned char). C says violating aliasing rules invokes undefined behavior (so don’t!). In this line … Read more

Unions and type-punning

To re-iterate, type-punning through unions is perfectly fine in C (but not in C++). In contrast, using pointer casts to do so violates C99 strict aliasing and is problematic because different types may have different alignment requirements and you could raise a SIGBUS if you do it wrong. With unions, this is never a problem. … Read more

Is it possible to write Quake’s fast InvSqrt() function in Rust?

I don’t know how to encode the float number using integer format. There is a function for that: f32::to_bits which returns an u32. There is also the function for the other direction: f32::from_bits which takes an u32 as argument. These functions are preferred over mem::transmute as the latter is unsafe and tricky to use. With … Read more

Purpose of Unions in C and C++

The purpose of unions is rather obvious, but for some reason people miss it quite often. The purpose of union is to save memory by using the same memory region for storing different objects at different times. That’s it. It is like a room in a hotel. Different people live in it for non-overlapping periods … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)