0

Let's say I have an integer in the form of a hexadecimal like:

int x = 0x12BFDA09;

How could I convert this into a char array such that each hex digit would be one char. An example of the output from int x would be:

{'1', '2', 'B', 'F', 'D', 'A', '0', '9'}

Any help would be greatly appreciated!

3
  • 3
    Use sprintf(), e.g. char s[9]; int x = 0x12BFDA09; sprintf(s, "%08X", x); Commented Sep 22, 2022 at 20:46
  • Just to note: hexadecimal values are best handled as unsigned... One needs to take a bit of care about this distinction... Commented Sep 22, 2022 at 21:41
  • Do you want a null-terminated string or an unterminated byte array? sprintf() will make a string. You can copy the data apart from the null terminator to a byte array if necessary. Very often, a string is more useful than a byte array, though C can handle either as long as you're careful. Commented Sep 22, 2022 at 21:58

1 Answer 1

1

With the presumption that this is not a homework assignment for you to solve on your own, this code shows two alternatives, presented for educational purposes.

#include <stdio.h>

int main() {
    char a[8], b[8]; // two variations

    uint32_t x = 0x12BFDA09; // your "seed" value

    // 8 iterations for 8 characters
    for( int i = 8; --i >= 0; /* rent this space */ ) {

        // method 1 - lookup table translation
        a[i] = "0123456789ABCDEF"[ x & 0xF ];

        // method 2 - branchless translation
        uint8_t n = (uint8_t)(x & 0xF);
        b[i] = (char)( (n<10)*(n+'0') + (n>9)*(n+'7') );

        // shift to bring next bits into frame
        x >>= 4;
    }
    // verify function
    printf( "%c %c %c %c %c %c %c %c \n",
        a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] );
    printf( "%c %c %c %c %c %c %c %c \n",
        b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7] );

    // alternative way to print char array lacking '\0'
    printf( "a[] = %.8s, b[] = %.8s\n", a, b );

    return 0;
}
1 2 B F D A 0 9
1 2 B F D A 0 9
a[] = 12BFDA09, b[] = 12BFDA09

<sermon> If this is a homework assignment, you will have done injury to yourself by not working out the solution for yourself. Fakin' it is not makin' it. </sermon>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.