简体   繁体   中英

Convert array of bytes to uint64_t?

I have a large array of bytes called memory and I'm trying to convert 8 of those bytes to a uint64_t. I'm trying to print the number in big-endian.

I have this so far:

uint64_t value =  (uint64_t)(memory[256]) | //location contains byte 88
   (uint64_t)(memory[257]) << 8  |          //77
   (uint64_t)(memory[258]) << 16 |          //66
   (uint64_t)(memory[259]) << 24 |          //55
   (uint64_t)(memory[260]) << 32 |          //44
   (uint64_t)(memory[261]) << 40 |          //33
   (uint64_t)(memory[262]) << 48 |          //22
   (uint64_t)(memory[263]) << 56;           //11

I print like so:

printf("0x%x", value);

The output is 0x55667788 , but I want the output to be 0x1122334455667788 .

Any suggestions of how I can fix the above code to print 0x1122334455667788 ?

Solution: The print statement needed to be:

printf("0x%lx", value);

The format specifier %lx works because the unsigned long type happens to have at least 64 bits on your system. The C Standard does not guarantee that and indeed it has only 32 bits on 64-bit Microsoft Windows. unsigned long long is guaranteed to have at least 64 bits, so you could use this:

printf("0x%llx\n", (unsigned long long)value);

If your compiler and C library support C99 or a later standard, you can use the macros defined in <inttypes.h> :

printf("0x%" PRIx64 "\n", value);

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