问题描述
我要两个ASCII字节转换成一个十六进制字节。
例如。
I want to convert two ASCII bytes to one hexadecimal byte.eg.
的0x30 0x43中= GT;的0x0C,0x34 =的0x46 GT&; 0x4F
...
的ASCII字节是 0
和 9
或之间的字母A之间的数字。
和˚F
(仅大写),所以之间的的0x30
... 0x39
和×41
... 0×46
The ASCII bytes are a number between 0
and 9
or a letter between A
and F
(upper case only), so between 0x30
... 0x39
and 0x41
... 0x46
我知道如何构建 0x4F
与数字 0x34
和 0×46: 0x4F = 0x34 *为0x10 + 0×46
I know how "to construct" 0x4F
with the numbers 0x34
and 0x46 : 0x4F = 0x34 * 0x10 + 0x46
所以,其实我是一个ASCII字节十六进制值转换。
So, in fact, i would to convert one ASCII byte in hexadecimal value.
对于这一点,我可以建立和阵列分配的十六进制值到的ASCII字符:
For that, i can build and array to assign the hexadecimal value to the ASCII char :
0x30 => 0x00
0x31 => 0x01
...
0x46 => 0x0F
不过,也许有一个最«正确»的解决方案。
But, maybe it have a most « proper » solution.
该程序将在一个AVRμC运行,并编译 AVR-GCC
,所以 scanf()的
/ 的printf()
解决方案是不适合的。
The program will be run on an AVR µC and is compiled with avr-gcc
, so scanf()
/ printf()
solutions aren't suitable.
你有一个想法?
谢谢
Have you got an idea ?Thanks
推荐答案
我不能让你的例子意义,但如果你想转换包含十六进制ASCII字符到字节值的字符串(例如,因此字符串56 成为字节0x56,你可以使用这个(假定您的系统使用的是ASCII)
i can't make sense of your examples, but if you want to convert a string containing hexadecimal ascii characters to its byte value (e.g. so the string "56" becomes the byte 0x56, you can use this (which assumes your system is using ASCII)
uint8_t*
hex_decode(const char *in, size_t len,uint8_t *out)
{
unsigned int i, t, hn, ln;
for (t = 0,i = 0; i < len; i+=2,++t) {
hn = in[i] > '9' ? in[i] - 'A' + 10 : in[i] - '0';
ln = in[i+1] > '9' ? in[i+1] - 'A' + 10 : in[i+1] - '0';
out[t] = (hn << 4 ) | ln;
}
return out;
}
您会使用它像如
char x[]="1234";
uint8_t res[2];
hex_decode(x,strlen(x),res);
和RES(其中必须至少在参数的长度的一半)现在包含2个字节0x12,0x34
And res (which must be at least half the length of the
in
parameter) now contains the 2 bytes 0x12,0x34
还要注意的是这个code需要十六进制字母AF是资本,AF不会做(和它不会做任何错误检查 - 所以你必须将它传递有效的东西)。
Note also that this code needs the hexadecimal letters A-F to be capital, a-f won't do (and it doesn't do any error checking - so you'll have to pass it valid stuff).
这篇关于在一个字节转换成两个ASCII十六进制字符(ASCII两个字节)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!