C语言 如何从 ASCII 转换为十六进制,反之亦然?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3212848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:49:53  来源:igfitidea点击:

How to convert from ASCII to Hex and vice versa?

c

提问by kiran

I need to convert ASCIIto HEXand HEXto ASCIIby using a C program.
How can I do that?

我需要转换ASCIIHEXHEXASCII通过使用一个C程序。
我怎样才能做到这一点?

回答by Eddie Sullivan

Here's a simplistic function to convert one character to a hexadecimal string.

这是将一个字符转换为十六进制字符串的简单函数。

char hexDigit(unsigned n)
{
    if (n < 10) {
        return n + '0';
    } else {
        return (n - 10) + 'A';
    }
}

void charToHex(char c, char hex[3])
{
    hex[0] = hexDigit(c / 0x10);
    hex[1] = hexDigit(c % 0x10);
    hex[2] = '##代码##';
}

回答by Goz

Its pretty easy. Scan through character by character ... best to start from the end. If the character is a number between 0 and 9 or a letter between a and f then place it in the correct position by left shifting it by the number of digits you've found so far.

它很容易。逐个字符扫描...最好从结尾开始。如果字符是 0 到 9 之间的数字或 a 和 f 之间的字母,则将其左移到目前为止找到的数字位数,从而将其放置在正确的位置。

For converting to a string then you do similar but first you mask and right shift the values. You then convert them to the character and place them in the string.

为了转换为字符串,您可以执行类似的操作,但首先要屏蔽并右移值。然后将它们转换为字符并将它们放入字符串中。