简体   繁体   English

转换Long-> Hex,然后将该Hex分配给C中的Char

[英]Converting Long -> Hex, then assigning that Hex to a Char in C

I am using a function that calculates a 16bit CRC checksum. 我正在使用一个计算16位CRC校验和的函数。

The function produces a LONG containing the checksum (base 10 number format). 该函数产生一个包含校验和(以10为底的数字格式)的LONG。 Of course, this can be printed to the console in it's hex equivalent as follows: 当然,可以将其打印为十六进制形式的控制台内容,如下所示:

printf("Checksum:  0x%x\n", crctablefast((unsigned char *)string, datalength));

For a given 20-byte char array being checked, it would produce the checksum 23277 in Hex format: 对于要检查的给定20字节char数组,它将产生十六进制格式的校验和23277:

Checksum:  5AED

I need to store the check sum as char in the 21st and 22nd places in the char array as the following: 我需要将校验和作为char存储在char数组的第21和22位,如下所示:

Char [20] = 0x5A
Char [21] = 0xED

The problem is that functions like scanf and sscanf, the best I can do is to assign the characters literally, as follows: 问题是像scanf和sscanf这样的函数,我能做的最好的就是按字面值分配字符,如下所示:

Char [20] = "0x5A"
Char [21] = "0xED"

...which is no good. ...这不好

What can I do to take two characters at a time, and use those to assign a hex value to a char? 我怎样做才能一次取两个字符,并用这些字符为一个char分配一个十六进制值? Or is there a much easier way in general? 还是总体上有一种更简单的方法?

Thank you in advance! 先感谢您!

It can be saved like this into a character or char array: 可以像这样将其保存到字符或char数组中:

Char [20]=(char) 0x5A; 字符[20] =(char)0x5A; Char [21]=(char) 0xED; 字符[21] =(char)0xED;

In this way it will save the character equivalent for the integer value of the hex number and you can convert it back by casting and use it. 这样,它将保存与十六进制整数值等效的字符,您可以通过强制转换并使用它来将其转换回来。

Well, nothing in the background is in hex, everything in machine is in binary, while human do things in decimal. 嗯,背景中没有东西是十六进制的,机器中的所有东西都是二进制的,而人类则以十进制表示。 So, hex is a man machine interface, a representation only. 因此,十六进制是人机界面,仅表示形式。

Use bit masks: 使用位掩码:

ch[20] = (crc >> 8) & 0xff;
ch[21] = crc & 0xff;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM