C++ Logo


Advanced search

Re: std::atomic_ref<T> enables mixed size and mixed atomicity accesses which are not defined under C++11 memory model

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Thu, 26 May 2022 14:54:26 +0300
On 5/26/22 12:46, Andy Wang via Std-Discussion wrote:
>> there is no "array of int16_t" object at x
> I replied to language.lawyer earlier bit forgot to reply all so it's not
> on the list - is there no proper way at all in C++ to read/get a
> reference to the top 16 bit of a int32_t?

If you want to just obtain the most significant half of an integer,
what's wrong with a shift?

int16_t hi = value32 >> 16;

If you want to analyze and interpret binary representation of an
integer, you're in the implementation-defined territory and will have to
deal with things like endianness. In this case you will address the
integer as bytes, either directly or through tools like memcpy.

const unsigned char* p = reinterpret_cast< const unsigned char* >(&value32);
// Works on little-endian targets
int16_t hi = p[2] | (p[3] << 8);
// or
int16_t hi;
std::memcpy(&hi, p + 2, sizeof(hi));

Received on 2022-05-26 11:54:29