0

How do I convert an array of bytes to an unsigned char (0 to 255, not -127 to 127)

If I'm not mistaken BitConverter only has BitConverter.ToChar which doesn't give me the result I'm looking for.

Thank you.

user1768788
  • 1,265
  • 1
  • 10
  • 29
  • 1
    @DanielA.White Nah, what is called a `System.Char` in .NET is a UTF-16 code unit which consists of sixteen bits. It may be a lower or upper part of a surrogate pair, of course, or it may code a combining character. But a `Char` in .NET is not 8 bits. – Jeppe Stig Nielsen Jan 28 '17 at 19:54
  • What are the types you ask for? Signed 8-bit integers are called `sbyte` in C# (`System.SByte` in the framework). Unsigned 8-bit integers are called `byte` (`System.Byte`). You say char, but in C# the keyword `char` is used for a UTF-16 code unit whose range is from `0` to `65535`. – Jeppe Stig Nielsen Jan 28 '17 at 19:59

3 Answers3

1

An array of bytes (byte[]) is already an array of items that are 0 to 255. chars in .NET are multibyte because they are Unicode. There's no such thing as a uchar in .NET.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

It depends on your usage. BitConverter.ToChar is used to convert 2 bytes from your byte array to an Unicode character (think of that as deserialization). In .NET, the char data type is used to represent an actual Unicode character, so it contains 2 bytes.

If your goal is to simply get an array of integers between 0 and 255, your byte array is exactly what you need.

Tomer
  • 1,606
  • 12
  • 18
0

You can convert the byte array to string

string str = System.Text.Encoding.ASCII.GetString(bytes);

or cast/convert them to char:

char[] chars = Array.ConvertAll(bytes, Convert.ToChar);
Slai
  • 22,144
  • 5
  • 45
  • 53
  • 1
    `Encoding.ASCII` is useful if all the bytes are in the range `0` through `127`. Otherwise, choose a "codepage" such as `string str = (new System.Text.Encoding("Windows-1252")).GetString(bytes);`. – Jeppe Stig Nielsen Jan 28 '17 at 20:08