Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract 32bit from 64bit integer

I have an uint64_t integral number and extracted the last 32bit into a uint32_t number by the following code:

uint32_t getLast(uint64_t v){
      uint64_t t= v >> 32;
      return  reinterpret_cast<uint32_t &>( t ); // type-punned pointer warning
}

int main()
{
    uint64_t a = 1l << 33 | 1l << 3;
    std::cout << getLast(a) << std::endl; // prints 2
}

This code gives the warning:

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
       return  reinterpret_cast<uint32_t &>( t );

I want to fix this, but not by using a union type.

The reinterprete_cast gives undefined behaviour, when accessing the data (copying the reinterpreted stuff into the return value) (i think?)

Another solution which seems to work?

 uint32_t getLast(uint64_t v){

    return (v >> 32) // conversion from bitshifted 64bit to 32bit, but what is with overflow?
 }

I am bit confused, about the undefined behaviour of reinterpret_cast? So how should I use reinterpret_cast, i thought that this example is the archi-typical usage pattern? Will the second method work safely too?

like image 762
Gabriel Avatar asked Mar 16 '26 11:03

Gabriel


1 Answers

You should just static_cast<uint32_t>. reinterpret_cast is pretty much exclusively used for highly dodgy and probably illegal pointer casting.

like image 195
Puppy Avatar answered Mar 18 '26 00:03

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!