在C中将十六进制转换为字符串? [英] Converting hex to string in C?

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

问题描述

你好我正在使用digi dynamic c。我试图将其转换为字符串

  char readingreg [4]; 
readingreg [0] = 4a;
readingreg [1] = aa;
readingreg [2] = aa;
readingreg [3] = a0;

目前,当我执行 printf 如下所示:

  printf(This is element 0:%x \\\
,readingreg [0]);

但我想要这个字符串,所以我可以使用 printf $> $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$> printf(这是元素0:%s \ n,readingreg [0]) ;

我必须通过TCP / IP端口发送readreg数组,我需要将它作为串。我似乎无法将其转换为字符串。谢谢你的帮助。
另外如果有人可以告诉我如何一次完成每个元素而不是整个数组,那就没问题了,因为只会有4个元素。

解决方案

0xaa 当plain char 签名时溢出,使用 unsigned char

  #include< stdio.h> 

int main(void)
{
unsigned char readingreg [4];
readingreg [0] = 0x4a;
readingreg [1] = 0xaa;
readingreg [2] = 0xaa;
readingreg [3] = 0xa0;
char temp [4];

sprintf(temp,%x,readingreg [0]);
printf(这是元素0:%s \ n,temp);
返回0;
}


Hello I am using digi dynamic c. I am trying to convert this in to string

char readingreg[4];
readingreg[0] = 4a;
readingreg[1] = aa;
readingreg[2] = aa;
readingreg[3] = a0;

Currently when I do printf statements it has to be like this:

printf("This is element 0: %x\n", readingreg[0]);

But I want this in string so I can use printf statement like this

  printf("This is element 0: %s\n", readingreg[0]);

I am essentialy sending the readingreg array over TCP/IP Port, for which I need to have it as string. I cant seem to be able to convert it into string. Thanks for your help. Also if someone can tell me how to do each element at a time rather than whole array, that would be fine to since there will only be 4 elements.

解决方案

0xaa overflows when plain char is signed, use unsigned char:

#include <stdio.h>

int main(void)
{
    unsigned char readingreg[4];
    readingreg[0] = 0x4a;
    readingreg[1] = 0xaa;
    readingreg[2] = 0xaa;
    readingreg[3] = 0xa0;
    char temp[4];

    sprintf(temp, "%x", readingreg[0]);
    printf("This is element 0: %s\n", temp);
    return 0;
}

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

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