Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

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 137 views
1 answer 140 views
1 answer 118 views
1 answer 108 views
1 answer 119 views
1 answer 97 views
1 answer 109 views
...