Nimaid
Nimaid

Reputation: 319

How To Convert a Single Byte to a String

I am using C# in Visual Studio 2010.

I want to convert a byte (8 bit int) to a string that's one character long. I need to do this because I want to send the byte value over serial to an Arduino.

For example, let's say

byte myByte = 49;

49 is the ASCII code for the character "1". I want to convert myByte into myString, such that if I did

serialport1.Write(myString);

It would function the same as

serialport1.Write("1");

Can anyone help me out?

Upvotes: 9

Views: 35125

Answers (6)

call-me
call-me

Reputation: 726

A simple solution is casting the byte to a char, then converting it to a string:

    public string SingleByteToString(byte ಠ_ಠ)
    {
        return ((char)(ಠ_ಠ)).ToString();
    }

Upvotes: 1

user8675309
user8675309

Reputation: 631

In case it helps anyone else: I had to do something similar in a loop and had issues getting the resultant string to print. The answer was to use spender's solution from above, but wrapped to check for null bytes before adding to my string:

string result = "";
foreach (byte myByte in myArray)
{
    if (myByte != (byte)00000000)
    {
        result += System.Text.Encoding.ASCII.GetString(new[]{myByte})
    }
}

Upvotes: 1

Tom Blodget
Tom Blodget

Reputation: 20812

Are you sure want to use ASCII?

If so, you should protect yourself from unconvertible data. One way is to have an exception thrown when the data is not ASCII:

var bytes = new Byte[]{myByte};
var encoding = Encoding.GetEncoding("US-ASCII", new EncoderExceptionFallback(), 
          new DecoderExceptionFallback());
var myString = encoding.GetString(bytes);

System.Text.Encoding.ASCII would replace unconvertible data with ?, which silently covers up problems and creates strange symptoms.

Upvotes: 1

Dali T
Dali T

Reputation: 1

Try this :

byte byteVal = 49;
serialport1.Write(System.Convert.ToString(byteValue));

Upvotes: 0

spender
spender

Reputation: 120548

System.Text.Encoding.ASCII.GetString(new[]{myByte})

Upvotes: 20

escargot agile
escargot agile

Reputation: 22399

serialport1.Write(Convert.ToChar(myByte).ToString());

See also: Convert.ToChar Method (Byte)

Upvotes: 2

Related Questions