Home > OS >  convert 4 byte hexadecimal to char array in C
convert 4 byte hexadecimal to char array in C

Time:09-23

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!

CodePudding user response:

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>

  •  Tags:  
  • chex
  • Related