[英]Convert ascii char[] to hexadecimal char[] in C
我试图将ASCII中的char []转换为十六进制的char []。
像这样的东西:
你好 - > 68656C6C6F
我想通过键盘读取字符串。 它必须是16个字符长。
这是我的代码。 我不知道该怎么做。 我读了关于strol但我认为它只是将str数转换为int hex ...
#include <stdio.h>
main()
{
int i = 0;
char word[17];
printf("Intro word:");
fgets(word, 16, stdin);
word[16] = '\0';
for(i = 0; i<16; i++){
printf("%c",word[i]);
}
}
我正在使用fgets,因为我读的比fgets好,但我可以在必要时更改它。
与此相关,我试图转换uint8_t数组中读取的字符串,将每个2字节连接在一起以获取十六进制数。
我有这个功能,我在arduino中使用了很多,所以我认为它应该在正常的C程序中工作没有问题。
uint8_t* hex_decode(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]|32) - 'a' + 10 : in[i] - '0';
ln = in[i+1] > '9' ? (in[i+1]|32) - 'a' + 10 : in[i+1] - '0';
out[t] = (hn << 4 ) | ln;
printf("%s",out[t]);
}
return out;
}
但是,每当我在代码中调用该函数时,我都会遇到分段错误。
将此代码添加到第一个答案的代码中:
uint8_t* out;
hex_decode(key_DM, sizeof(out_key), out);
我试图传递所有必要的参数并输出我需要的数组,但它失败了......
#include <stdio.h>
#include <string.h>
int main(void){
char word[17], outword[33];//17:16+1, 33:16*2+1
int i, len;
printf("Intro word:");
fgets(word, sizeof(word), stdin);
len = strlen(word);
if(word[len-1]=='\n')
word[--len] = '\0';
for(i = 0; i<len; i++){
sprintf(outword+i*2, "%02X", word[i]);
}
printf("%s\n", outword);
return 0;
}
替换这个
printf("%c",word[i]);
通过
printf("%02X",word[i]);
使用%02X
格式参数:
printf("%02X",word[i]);
更多信息可以在这里找到: http : //www.cplusplus.com/reference/cstdio/printf/
void atoh(char *ascii_ptr, char *hex_ptr,int len)
{
int i;
for(i = 0; i < (len / 2); i++)
{
*(hex_ptr+i) = (*(ascii_ptr+(2*i)) <= '9') ? ((*(ascii_ptr+(2*i)) - '0') * 16 ) : (((*(ascii_ptr+(2*i)) - 'A') + 10) << 4);
*(hex_ptr+i) |= (*(ascii_ptr+(2*i)+1) <= '9') ? (*(ascii_ptr+(2*i)+1) - '0') : (*(ascii_ptr+(2*i)+1) - 'A' + 10);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.