[英]C conver unsigned char to HEX
is convert unsigned char / int to hex, trouble is no correct translate ascci table: original: 0D, converted: AD code: 将unsigned char / int转换为十六进制,麻烦的是没有正确的转换ascci表:原始:0D,转换:AD代码:
char int_to_hex(int d) {
if (d < 0) return -1;
if (d > 16) return -1;
if (d <= 9) return '0' + d;
d -= 10;
return (char)('A' + d);
}
void uint_to_hex(unsigned char in, char **out, int *olen) {
int i = 0;
int remain[2];
int result = (int)in;
while (result) {
remain[i++] = result % 16;
result /= (int)16;
}
for (i = 1; i >= 0; --i) {
char c = int_to_hex(remain[i]);
if( (int)c == -1 ) { continue; }
*((*out) + (*olen)) = (char)c; (*olen)++;
}
}
where is incorrect ?.. 哪里不正确?
First of all one hex digit will cover values from 0 (0) to 15 (F) not from 0 to 16 (as you seem to assume in int_to_hex
function). 首先,一个十六进制数字将覆盖从0(0)到15(F)的值,而不是从0到16的值(就像您在
int_to_hex
函数中所假定的int_to_hex
)。
Also you don't really need typecasting to char
in last return of that function. 另外,在该函数的最后一次返回中,您实际上并不需要类型转换为
char
。
In fact all typecasts here are rather unnecessary 实际上,这里的所有类型转换都是不必要的
And typecasting of literal 16
is purely absurd... 而字面量
16
类型转换纯粹是荒谬的...
And how sample input for uint_to_hex
is looking ? 以及
uint_to_hex
样本输入的uint_to_hex
如何? You are aware, that on input ( in
) you can pass only single char
acter ? 您是否知道,在输入(
in
)中只能传递单个char
?
I think that char pointer would suffice for out
- i mean, you want to return array, right ? 我认为字符指针就足够了
out
-我的意思是,你想返回数组,对不对? So instead of **
should be only singe *
. 因此,代替
**
应该只能是*
。
And I don't understand why olen
has to be pointer (and argument to function too). 而且我不明白为什么
olen
必须是指针(以及函数的参数)。
And you should try to write more concise and readable code, it will help you understand what you are doing too. 而且,您应该尝试编写更加简洁易读的代码,这将有助于您了解自己在做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.