Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string data from encoded bytes

Tags:

c#

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?

like image 813
Florim Maxhuni Avatar asked Feb 08 '11 07:02

Florim Maxhuni


People also ask

How do you get a byte from a string?

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) .

Can we convert byte to string in C#?

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.

Can we convert byte to string in Java?

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.


1 Answers

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);
like image 56
Marc Gravell Avatar answered Oct 02 '22 09:10

Marc Gravell