Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Convert a Single Byte to a String

Tags:

c#

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?

like image 733
Nimaid Avatar asked Mar 02 '14 23:03

Nimaid


People also ask

How do you turn a byte into a string?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.

Can we convert byte to string in Java?

So below code can also be used to convert byte array to String in Java. String str = new String(byteArray, StandardCharsets. UTF_8); String class also has a method to convert a subset of the byte array to String.

How many bytes is a string?

But what about a string? A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)


2 Answers

System.Text.Encoding.ASCII.GetString(new[]{myByte})
like image 107
spender Avatar answered Oct 19 '22 03:10

spender


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

See also: Convert.ToChar Method (Byte)

like image 43
Ilya Kogan Avatar answered Oct 19 '22 05:10

Ilya Kogan