您好,我正在尝试使用C将十进制值转换为十六进制,以便将其存储在我的变量char data[]
中,并在以后将数据用于其他用途。有人知道我怎么做吗?我是C语言新手
发布于 2012-12-13 12:11:42
如果您有一个存储在"char“变量中的数字,那么它将以二进制形式存储在机器中。打印变量时,可以选择变量的显示方式。例如,要以十进制显示它,您可以执行以下操作:
printf("The value in decimal is %d\n", x);
要以十六进制显示它,您可以执行以下操作:
printf("The value in hex is %x\n", x);
您可能希望查看一本关于C的书并检查printf格式选项,因为您可以对值的显示方式做很多事情(作为字符、八进制、填充等)。请记住,计算机只以一种方式存储数据。不存在从一种表示到另一种表示的转换。
发布于 2012-12-13 11:58:37
您可以使用%x
格式说明符和sprintf
。传入data
作为第一个参数,将打印的值作为最后一个参数:
int value = 12345;
char data[16];
sprintf(data, "%x", value); // This produces 3039
Link to ideone.
发布于 2017-07-13 19:25:13
#include <stdio.h>
typedef unsigned char UCHAR;
typedef char CHAR;
typedef unsigned short int UINT16;
typedef unsigned int UINT32;
typedef float FLOAT32;
typedef int INT32;
typedef short int INT16;
void DecimalToHex(UCHAR *ucHexStringStored, UINT32 nDecimalValue){
INT16 anHexValueStored[8];
INT16 nPartialRemainder,ncnt1;
UINT16 unLengthOfHexString = 0;
while(nDecimalValue) {
nPartialRemainder = nDecimalValue % 16;
if(nPartialRemainder>9){
nPartialRemainder = nPartialRemainder-10 + 17;
}
anHexValueStored[unLengthOfHexString++] = nPartialRemainder + '0';
nDecimalValue /= 16;`enter code here`
}
CHAR ucHexStringConverted[unLengthOfHexString];
for(ncnt1 = unLengthOfHexString-1 ; ncnt1>=0 ; ncnt1--){
ucHexStringConverted[unLengthOfHexString-ncnt1-1]=anHexValueStored[ncnt1];
};
ucHexStringConverted[unLengthOfHexString]='\0';
for(ncnt1=0 ; ncnt1 <= unLengthOfHexString ; ncnt1++)
ucHexStringStored[ncnt1]=ucHexStringConverted[ncnt1];
}
int main() {
UCHAR c[8];
DecimalToHex(c,-6243);//Decimal value and it will be converted to Hex
printf("%s",c);
return 0;
}
en
在此处输入代码
https://stackoverflow.com/questions/13852687
复制相似问题