6

How can I convert uint64_t to uint8_t[8] without loosing information in C++?

I tried the following:

uint64_t number = 23425432542254234532;
uint8_t result[8];
for(int i = 0; i < 8; i++) {
    std::memcpy(result[i], number, 1);
}
2
  • How did your attemt fail? Does it not compile? Do you get wrong output?
    – eerorika
    Feb 2, 2016 at 12:14
  • 1
    uint64_t is 64 bits if your platform supports it. The literal on the first line is to large to fit in that type. Feb 2, 2016 at 12:25

7 Answers 7

13

You are almost there. Firstly, the literal 23425432542254234532 is too big to fit in uint64_t.

Secondly, as you can see from the documentation, std::memcpy has the following declaration:

void * memcpy ( void * destination, const void * source, size_t num );

As you can see, it takes pointers (addresses) as arguments. Not uint64_t, nor uint8_t. You can easily get the address of the integer using the address-of operator.

Thridly, you are only copying the first byte of the integer into each array element. You would need to increment the input pointer in every iteration. But the loop is unnecessary. You can copy all bytes in one go like this:

std::memcpy(result, &number, sizeof number);

Do realize that the order of the bytes depend on the endianness of the cpu.

0
12

First, do you want the conversion to be big-endian, or little-endian? Most of the previous answers are going to start giving you the bytes in the opposite order, and break your program,` as soon as you switch architectures.

If you need to get consistent results, you would want to convert your 64-bit input into big-endian (network) byte order, or perhaps to little-endian. For example, on GNU glib, the function is GUINT64_TO_BE(), but there is an equivalent built-in function for most compilers.

Having done that, there are several alternatives:

Copy with memcpy() or memmove()

This is the method that the language standard guarantees will work, although here I use one function from a third-party library (to convert the argument to big-endian byte order on all platforms). For example:

#include <stdint.h>
#include <stdlib.h>

#include <glib.h>

union eight_bytes {
  uint64_t u64;
  uint8_t b8[sizeof(uint64_t)];
};

eight_bytes u64_to_eight_bytes( const uint64_t input )
{
  eight_bytes result;
  const uint64_t big_endian = (uint64_t)GUINT64_TO_BE((guint64)input);

  memcpy( &result.b8, &big_endian, sizeof(big_endian) );
  return result;
}

On Linux x86_64 with clang++ -std=c++17 -O, this compiles to essentially the instructions:

bswapq  %rdi
movq    %rdi, %rax
retq

If you wanted the results in little-endian order on all platforms, you could replace GUINT64_TO_BE() with GUINT64_TO_LE() and remove the first instruction, then declare the function inline to remove the third instruction. (Or, if you’re certain that cross-platform compatibility does not matter, you might risk just omitting the normalization.)

So, on a modern, 64-bit compiler, this code is just as efficient as anything else. On another target, it might not be.

Type-Punning

The common way to write this in C would be to declare the union as before, set its uint64_t member, and then read its uint8_t[8] member. This is legal in C.

I personally like it because it allows me to express the entire operation as static single assignments.

However, in C++, it is formally undefined behavior. In practice, all C++ compilers I’m aware of support it for Plain Old Data (the formal term in the language standard), of the same size, with no padding bits, but not for more complicated classes that have virtual function tables and the like. It seems more likely to me that a future version of the Standard will officially support type-punning on POD than that any important compiler will ever break it silently.

The C++ Guidelines Way

Bjarne Stroustrup recommended that, if you are going to type-pun instead of copying, you use reinterpret_cast, such as

uint8_t (&array_of_bytes)[sizeof(uint64_t)] =
      *reinterpret_cast<uint8_t(*)[sizeof(uint64_t)]>(
        &proper_endian_uint64);

His reasoning was that both an explicit cast and type-punning through a union are undefined behavior, but the cast makes it blatant and unmistakable that you are shooting yourself in the foot on purpose, whereas reading a different union member than the active one can be a very subtle bug.

5
  • 2
    this should be the accepted answer! To OP, please consider accepting to make sure future question readers are guaranteed to see it. May 5, 2020 at 16:30
  • You wrote "Most of the previous answers are going to abruptly start giving you the byte 0x23 instead of 0x32 as soon as you switch architectures.", but that suggests nibbles (4-bit groups) are being exchanged, while endiannes issues are about byte ordering, not nibble ordering. You should probably update the example, otherwise the note about endianness is perfect (and very important). Jun 24, 2020 at 14:51
  • @MatthijsKooijman If you go back to the original post, the eighth byte of the array in the MWE was 0x23. That this also happens be a transposition of the hex digits in the first byte of the array is pure coincidence.
    – Davislor
    Jun 24, 2020 at 17:33
  • @MatthijsKooijman Actually, looking back at it, it was too long to fit in an uint54_t and also not specified as a hexadecimal number. So it’s actually undefined behavior.
    – Davislor
    Jun 24, 2020 at 17:39
  • Ah, I see. Nevertheless, your updated answer removes the confusion. Thanks! Jun 25, 2020 at 11:49
5

If I understand correctly you can do this that way for instance:

uint64_t number = 23425432542254234532;
uint8_t *p = (uint8_t *)&number;
//if you need a copy
uint8_t result[8];
for(int i = 0; i < 8; i++) {
    result[i] = p[i];
}
6
  • 5
    You are aliasing types here uint8_t *p = (uint8_t *)&number. This is not allowed with the strict aliasing rules.
    – Niall
    Feb 2, 2016 at 12:26
  • 2
    @Niall - any pointer can be converted to unsigned char* without violating strict aliasing. And uint8_t, if it exists, will be a typedef for unsigned char. Feb 2, 2016 at 14:37
  • 1
    @PeteBecker. Is uint8_t specified to be an unsigned char or are just most implementations such?
    – Niall
    Feb 2, 2016 at 14:38
  • 1
    @Niall - uint8_t is required to be a typedef for an unsigned 8-bit integral type. The only standard integer type that meets those requirements is unsigned char. Formally, I suppose, an implementation could use its own internal type, but that's an awful lot of work to go through just to screw their users. <g> Feb 2, 2016 at 14:45
  • 1
    uint8_t is not required to be a character type. Future standards should include std::byte in the list of types allowed to alias anything, though, which may make that a better choice than uint8_t.
    – Ben Voigt
    Mar 14, 2018 at 15:37
3

When copying memory around between incompatible types, the first thing to be aware of is strict aliasing - you don't want to alias pointers incorrectly. Alignment is also to be considered.

You were almost there, the for is not needed.

uint64_t number = 0x2342543254225423; // trimmed to fit
uint8_t result[sizeof(number)];
std::memcpy(result, &number, sizeof(number));

Note: be aware of the endianness of the platform as well.

2

Either use a union, or do it with bitwise operations- memcpy is for blocks of memory and might not be the best option here.

uint64_t number = 23425432542254234532;
uint8_t result[8];
for(int i = 0; i < 8; i++) {
    result[i] = uint8_t((number >> 8*(7 - i)) & 0xFF);
}

Or, although I'm told this breaks the rules, it works on my compiler:

union
{
    uint64_t a;
    uint8_t b[8];
};

a = 23425432542254234532;
//Can now read off the value of b
uint8_t copy[8];
for(int i = 0; i < 8; i++)
{
    copy[i]= b[i];
}
4
  • 2
    Not quite sure why this was downvoted. Especially the first solution is the better one in my opinion, since it doesn't rely on details like endianness or create potential aliasing problems that might cause stuff to break when using optimized code.
    – mindriot
    Feb 2, 2016 at 12:27
  • 2
    @mindriot I suspect that the downvote was for the second option, which breaks strict aliasing rules. But the first option is indeed good one (assuming it's correct, I didn't check), if the endianness is important, and htonl family of functions are not available.
    – eerorika
    Feb 2, 2016 at 12:31
  • @user2079303 Yes, I suspect so too. And that's why downvotes should always go along with a comment…
    – mindriot
    Feb 2, 2016 at 12:32
  • 1
    The union version likely works on all systems that have the fixed sized types defined. But the C++ standard says that writing to a and reading from b is undefined, because the union can only contain one of its members at a time.
    – Bo Persson
    Feb 2, 2016 at 12:46
0

The packing and unpacking can be done with masks. One more thing to worry about is the byte order. packing and unpacking should use the same byte order. Beware - This is not super efficient implementation and do not come with guarantees on small CPU that are not native 64-bit.

void unpack_uint64(uint64_t number, uint8_t *result) {

    result[0] = number & 0x00000000000000FF ; number = number >> 8 ;
    result[1] = number & 0x00000000000000FF ; number = number >> 8 ;
    result[2] = number & 0x00000000000000FF ; number = number >> 8 ;
    result[3] = number & 0x00000000000000FF ; number = number >> 8 ;
    result[4] = number & 0x00000000000000FF ; number = number >> 8 ;
    result[5] = number & 0x00000000000000FF ; number = number >> 8 ;
    result[6] = number & 0x00000000000000FF ; number = number >> 8 ;
    result[7] = number & 0x00000000000000FF ;

}



uint64_t  pack_uint64(uint8_t *buffer) {

    uint64_t value ;

    value = buffer[7] ;
    value = (value << 8 ) + buffer[6] ;
    value = (value << 8 ) + buffer[5] ;
    value = (value << 8 ) + buffer[4] ;
    value = (value << 8 ) + buffer[3] ;
    value = (value << 8 ) + buffer[2] ;
    value = (value << 8 ) + buffer[1] ;
    value = (value << 8 ) + buffer[0] ;

    return value ;

}
-1
#include<cstdint>
#include<iostream>

 struct ByteArray
{
    uint8_t b[8] = { 0,0,0,0,0,0,0,0 };
};

ByteArray split(uint64_t x)
{
    ByteArray pack;
    const uint8_t MASK = 0xFF;
    for (auto i = 0; i < 7; ++i)
    {
        pack.b[i] = x & MASK;
        x = x >> 8;
    }
    return pack;
}
int main()
{
    uint64_t val_64 = UINT64_MAX;
    auto pack = split(val_64);
    for (auto i = 0; i < 7; ++i)
    {
        std::cout << (uint32_t)pack.b[i] << std::endl;
    }
    system("Pause");
    return 0;
}

Although union approach which is addressed by Straw1239 is better and cleaner.Please do care about compiler/platform compatibility with endianness.

6
  • 1
    Union approach is not "better and cleaner", it's undefined behavior.
    – Ben Voigt
    Mar 14, 2018 at 15:37
  • @BenVoigt I have compiled and run with VC++ 2017 Mar 14, 2018 at 15:39
  • 1
    That proves nothing. You cannot test for undefined behavior, because the test results are undefined too.
    – Ben Voigt
    Mar 14, 2018 at 15:41
  • When the program contains undefined behavior, the compiler output can be anything too. The compiler could generate something totally different tomorrow and still be 100% compliant.
    – Ben Voigt
    Mar 14, 2018 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.