在C中将单个字符(十六进制数字)转换为整数 [英] Convert single Character (hex number) to Integer in C

查看:202
本文介绍了在C中将单个字符(十六进制数字)转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对于作业,我必须将字符( 0 - F )转换为整数( 0 - 15 ), 0 - 9 可以正常工作,但是如果给出任何字母,它会打印一个随机数:例如,对于 C ,它给出 19 ,对于 D 则返回 20

So for an assignment I have to convert a character (0-F) to an integer (0-15), 0-9 works fine, but if any letter is given, it prints a random number: For C for instance, it gives 19, for D is returns 20.

这是我的方法:

int char2int(char digit) {
    int i = 0;

    if (digit == 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9)
        i = digit - '0';
    else
    if (digit == 'A' || 'B' || 'C' || 'D' || 'E' || 'F')
        i = digit - '9';
    else
        i = -1;

    return i;
}

起初,我的if语句是这样的:

At first my if statements were like this:

if (digit => 0 && =< 9)

if (digit => A && =< F)

但这带来了许多错误。你可以说我不太了解C。我当前的If语句有效,但是我确定它的长度不必要。

But that gave a number of errors. You can tell I don't know C very well. My current If statement works but I'm sure it's unnecessarily long.

推荐答案


if(digit = = 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9)

if (digit == 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9)

条件表达式在C中不是这样。

This is not how conditional expressions work in C.

您需要将数字与每个数字进行比较单独的数字

You either need to compare digit against each of the numbers individually

if (digit == '0' || digit == '1' || digit == '2' ...

或巧妙地做到这一点:

if(digit >= '0' && digit <= '9')
                         ^^ not =<

请注意,由于要比较,我在数字周围加上了' 字母0 而不是数字的数字(这是不相同的,请参见此处)所有ASCII字符值)。

Notice that I put ' around the numbers because you want to compare the digit with the letter 0 and not the number (which is not the same see here for all the ASCII character values).

这篇关于在C中将单个字符(十六进制数字)转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆