I have an array of bytes that has come from a barcode reader (connected via a COM port) reading an ID Card. When I convert these, I can read some of the data, for example:
Name, Surname, City
etc, but if some of the data has some characters like 'Ë' or 'Ç', or some characters that are used in our language [ed: OP is in Pristina, Kosovo], I get '?'. How can I get these characters through decoding?
Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .
In C#, we can convert an array of bytes to string using classes like BitConverter, Encoding, MemoryStream, etc. The resulted string provided by the BitConverter class includes hexadecimal pairs. Using the Encoding class, we can convert string to byte[] and byte[] to a string using the same encoding scheme.
We can convert the byte array to String for the ASCII character set without even specifying the character encoding. The idea is to pass the byte[] to the String constructor.
You need to know the appropriate Encoding
that the device uses; it could be UTF-16, for example, in which case
string s = Encoding.Unicode.GetString(bytes);
or UTF-8:
string s = Encoding.UTF8.GetString(bytes);
but for regional encodings / code-pages you'll have to use:
string s = Encoding.GetEncoding(yourEncoding).GetString(bytes);
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