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?
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.
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.
But what about a string? A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)
System.Text.Encoding.ASCII.GetString(new[]{myByte})
serialport1.Write(Convert.ToChar(myByte).ToString());
See also: Convert.ToChar Method (Byte)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With