简体   繁体   English

如何将十六进制字符串转换为C#中ASCII值相同的字符串?

[英]How can convert a hex string into a string whose ASCII values have the same value in C#?

Assume that I have a string containing a hex value. 假设我有一个包含十六进制值的字符串。 For example: 例如:

string command "0xABCD1234";

How can I convert that string into another string (for example, string codedString = ... ) such that this new string's ASCII-encoded representation has the same binary as the original strings contents ? 如何将该字符串转换为另一个字符串(例如, string codedString = ... ),以使该新字符串的ASCII编码表示形式具有与原始字符串内容相同的二进制文件?

The reason I need to do this is because I have a library from a hardware manufacturer that can transmit data from their piece of hardware to another piece of hardware over SPI . 之所以需要这样做,是因为我有一个硬件制造商提供的库,可以通过SPI将数据从其硬件传输到另一硬件。 Their functions take strings as an input, but when I try to send "AA" I am expecting the SPI to transmit the binary 10101010, but instead it transmits the ascii representation of AA which is 0110000101100001. 它们的函数将字符串作为输入,但是当我尝试发送“ AA”时,我期望SPI传输二进制10101010,但相反,它将传输AA的ascii表示0110000101100001。

Also, this hex string is going to be 32 hex characters long (that is, 256-bits long). 另外,此十六进制字符串的长度将为32个十六进制字符(即256位长)。

string command = "AA";
int num = int.Parse(command,NumberStyles.HexNumber);
string bits = Convert.ToString(num,2); // <-- 10101010

I think I understand what you need... here is the main code part.. asciiStringWithTheRightBytes is what you would send to your command. 我想我了解您的需要...这是主要的代码部分。.asciiStringWithTheRightBytes是您要发送给命令的内容。

var command = "ABCD1234";
var byteCommand = GetBytesFromHexString(command);
var asciiStringWithTheRightBytes = Encoding.ASCII.GetString(byteCommand);

And the subroutines it uses are here... 它使用的子例程在这里...

static byte[] GetBytesFromHexString(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(byte)];
    for (var i = 0; i < str.Length; i++)
        bytes[i] = HexToInt(str[i]);
        return bytes;
}

static byte HexToInt(char hexChar)
{
    hexChar = char.ToUpper(hexChar);  // may not be necessary

    return (byte)((int)hexChar < (int)'A' ?
        ((int)hexChar - (int)'0') :
        10 + ((int)hexChar - (int)'A'));
}

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

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