How to convert string with binary number to hex in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

char* BinaryToHex(const char* str) {
    long decimalNumber = strtol(str, NULL, 2);
    char* hex = (char*)malloc(16 * sizeof(char)); 

    if (hex == NULL) {
        perror("Memory allocation failed");
        exit(EXIT_FAILURE);
    }

    snprintf(hex, 9, "%lX", decimalNumber); // Convert decimal to hexadecimal
    
    return hex;
}

int main() {
    const char* binaryNumber = "111101001101";
    char* hex = BinaryToHex(binaryNumber);

    printf("%s\n", hex);

    free(hex); 
    
    return 0;
}

 
 
/*
run:
 
F4D
 
*/

 



answered Jul 1, 2024 by avibootz

Related questions

2 answers 174 views
1 answer 164 views
1 answer 149 views
1 answer 132 views
1 answer 151 views
1 answer 113 views
1 answer 140 views
...