Karl
Karl

Reputation: 956

Convert a binary number to ascii characters

I am reading information from a device and it's returning data to me in integer format and I need to convert this to ASCII characters using C#.

The following is an example of the data I have to convert. I receive the integer value 26990 back from my device and I need to convert that to ASCII. I just happen to know that for this value, the desired result would be "ni".

I know that the integer value 26990 is equal to 696e in hex, and 110100101101110 in binary, but would like to know how to do the conversion as I can't work it out for myself.

Can anyone help please?

Many thanks,

Karl

Upvotes: 3

Views: 7644

Answers (3)

Lance U. Matthews
Lance U. Matthews

Reputation: 16612

If the device is sending bytes you can use something like this:

byte[] bytes = new byte[] { 0x69, 0x6e };
string text = System.Text.Encoding.ASCII.GetString(bytes);

Otherwise, if the device is sending integers you can use something like this:

byte[] bytes = BitConverter.GetBytes(26990);
string text = System.Text.Encoding.ASCII.GetString(bytes, 0, 2);

In either case, text will contain "ni" after that executes. Note that in the latter you may have to deal with endianness issues.

Further reference:

Upvotes: 0

adelphus
adelphus

Reputation: 10316

Use BitConverter and Encoding to perform the conversion:

class Program
{
    public static void Main()
    {
        int d = 26990;
        byte[] bytes = BitConverter.GetBytes(d);
        string s = System.Text.Encoding.ASCII.GetString(bytes);
        // note that s will contain extra NULLs here so..
        s = s.TrimEnd('\0');
    }
}

Upvotes: 0

L.B
L.B

Reputation: 116188

int i = 26990;
char c1 = (char)(i & 0xff);
char c2 = (char)(i >> 8);

Console.WriteLine("{0}{1}", c1, c2);

Upvotes: 5

Related Questions