I want to get the low 32 bit of a int64 as int32

前端 未结 5 1247
梦如初夏
梦如初夏 2021-01-04 05:02

I have an Int64 value, but I only need the lower 32 bits. Thus I want a quick way to get the Int32 value from the lower 32 bits of the Int64 value.

Thanks

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 05:41

    In C/C++ the best way (in my opinion) is to use a union. For example the following function uses an anonymous union to extract the lower-order 32 bits from a 64 bit integer.

    uint32_t lower_32_bits(uint64_t value) {
        union { uint64_t value; struct { uint32_t high, low; }; } converter;
        converter.value = value;
        return converter.low;
    }
    

    This union trick can be used for all sorts of things, like getting the bits of a floating point value into an integer of the same bitlength, e.g. for doing bitwise operations and other hacks.

提交回复
热议问题