2

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?

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. 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.

Also, this hex string is going to be 32 hex characters long (that is, 256-bits long).

4

2 回答 2

4
string command = "AA";
int num = int.Parse(command,NumberStyles.HexNumber);
string bits = Convert.ToString(num,2); // <-- 10101010
于 2013-06-21T20:34:06.640 回答
-2

我想我明白你需要什么......这是主要的代码部分...... asciiStringWithTheRightBytes 是你要发送给你的命令的内容。

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

它使用的子程序在这里......

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'));
}
于 2013-06-21T21:15:42.413 回答