简体   繁体   中英

How to copy part of int64_t to char[4] in c++?

I have a variable:

int64_t label : 40

I want to take the 32 lower bits and put them in a variable of type:

char nol[4]

How can I do that in c++?

Depends on what you mean by "lower" bits. The word "lower" normally implies lower memory address. But that's rarely useful. You may be thinking of least significant instead, which is more commonly useful.

You must also consider what order you want the bytes to be in the array. When copying the lower bytes, you typically want to keep the bytes in the same order as in the integer ie native endianness. When copying least significant bytes, you typically want a specific order which may differ from the native endianness ie either big or little endian. Big endian is conventionally used in.network communication.

If the number of bits to copy is not a multiple of byte size, then copying the incomplete byte adds some complexity.

Copying the lower bytes in native order is very simple:

char nol[32 / CHAR_BIT];
std::memcpy(nol, &label, sizeof nol);

Here is an example of copying least significant bytes in big endian order:

for (int i = 0; i < sizeof nol; i++) {
    nol[sizeof nol - i] = label >> CHAR_BIT * i & UCHAR_MAX;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM