Convert binary number to ascii characters

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

Below is an example of the data I need to transform. I am getting an integer value 26990 from my device and I need to convert it to ASCII. I just know that for this value, the desired result is "ni".

I know that the integer value 26990 is 696e in hex and 110100101101110 in binary, but would like to know how to do the conversion as I cannot solve it myself.

Can anyone please help?

Many thanks,

Charles

+3


source to share


3 answers


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

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

      



+5


source


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

      



text

Will contain "ni"

after that anyway . Please note that in the latter case, you may have to deal with content issues.

Further link:

0


source


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

      

0


source







All Articles