How to convert uint32_t number to char[8]?

dasfex

Suppose we have a string s = "453acd0f". Now I want to do something like this:

uint32_t res = 0;
for (size_t i = 0; i < 8; ++i) {
    res |= ConvertCharToHexNumber(s[8 - i - 1]) << (i * 4);
}

But how I should do this if I have a uint32_t var variable which I read from a binary file?

Waqar

The simplest way to convert a 4 byte uint32_t into char[8]:

    uint32_t var = 100;
    char res[8]{};
    res[0] = (var >> 28) & 0XF;
    res[1] = (var >> 24) & 0XF;
    res[2] = (var >> 20) & 0XF;
    res[3] = (var >> 16) & 0XF;
    res[4] = (var >> 12) & 0XF;
    res[5] = (var >> 8)  & 0XF;
    res[6] = (var >> 4)  & 0XF;
    res[7] = (var >> 0)  & 0XF;

You can reduce this to a loop:

    int shiftby = 32;
    for (int i = 0; i < 8; i++) {
        res[i] = (var >> (shiftby -= 4)) & 0xF;
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to convert uint32_t to unsigned char array?

How to convert a string to uint32_t

Convert Char* Variable To uint32_t in C

How to convert uint32_t to double or float and print?

How to safely extract a signed field from a uint32_t into a signed number (int or uint32_t)

How to convert uint16_t[2N] to uint32_t[N] effectively?

Variable number of bytes to Uint32_t

Is there a way to convert void (*)(uint32_t, void (*)(uint32_t)) to std::function<void(uint32_t, std::function<void(uint32_t)>)>?

char[] to uint32_t not working properly

Memcpy uint32_t into char*

Convert IP address in sockaddr to uint32_t

Convert uint32_t to double between 0 and 1

In c, how is uint8_t structure_member[4] different than uint32_t structure_member in regards to structure padding?

how to convert char to number in matlab?

How to convert char to number with mask

how to convert a numeric into a char number?

How to convert Uint8List to decimal number in Dart?

Convert to UInt32 in Swift from NS_ENUM uint32_t in Objective-C

error: invalid conversion from 'char*' to 'uint32_t

Understanding uint32_t char typecast (Bytes)

compare const char * string to uint32_t value at compilation

Concatenate char[] and uint32_t in C++

How to get a unique value in Java that corresponds to uint32_t?

How to pass uint32_t * as a property to QML

How to get a pointer to the bytes of a uint32_t

How to save the uint32_t mask as a pointer variable?

What is the fastest way to convert a large c-array of char8 to short16?

How to convert [4]uint8 into uint32 in Go?

How to convert uint16_t number to ASCII HEX?