orion314
orion314

Reputation: 15

C programming Hex to Char

What I'm trying to do is have the user input a hex number this number will then be converted to a char and displayed to the monitor this will continue until an EOF is encountered.I have the opposite of this code done which converts a char to a hex number. The problem I'm running into is how do i get a hex number from the user I used getchar() for the char2hex program. Is there any similar function for hex numbers?

this is the code for the char2hex program

#include <stdio.h>
int main(void) {
    char myChar;
    int counter = 0;

    while (EOF != (myChar = getchar())) {
        /* don't convert newline into hex */
        if (myChar == '\n')
            continue;
        printf("%02x ", myChar);

        if (counter > 18) {
            printf("\n");
            counter = -1;
        }
        counter++;
    }
    system("pause");
    return 0;
}

this is what i want to the program to do except it would do this continuously

#include <stdio.h>
int main() {
    char myChar;

    printf("Enter any hex number: ");
    scanf("%x", &myChar);

    printf("Equivalent Char is: %c\n", myChar);

    system("pause");

    return 0;
}

any help would be appreciated thank you

Upvotes: 1

Views: 11433

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40155

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(void) {
    int myChar;
    int counter = 0;
    char buff[3] = {0};

    while (EOF != (myChar = getchar())) {
        if(isxdigit(myChar)){
            buff[counter++] = myChar;
            if(counter == 2){
                counter = 0;
                myChar = strtol(buff, NULL, 16);
                putchar(myChar);
            }
        }
    }
    printf("\n");
    system("pause");
    return 0;
}

Upvotes: 3

Erik
Erik

Reputation: 121

Because chars and ints can be used interchangably in C, you can use the following code:

int main(void) {
    int myChar;

    printf("Enter any hex number: ");
    scanf("%x", &myChar);

    printf("Equivalent Char is: %c\n", myChar);

    system("pause");

    return 0;
}

If you want it to loop then just enclose it in the while loop as in your example code.

Edit: You can try out the working code here http://ideone.com/yyvz85

Upvotes: 1

Related Questions