user2211907
user2211907

Reputation:

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?

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

Upvotes: 2

Views: 2568

Answers (2)

Kevin
Kevin

Reputation: 4636

I think I understand what you need... here is the main code part.. asciiStringWithTheRightBytes is what you would send to your command.

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'));
}

Upvotes: -2

I4V
I4V

Reputation: 35353

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

Upvotes: 4

Related Questions