dimanche 2 août 2015

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?

Aucun commentaire:

Enregistrer un commentaire