Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

German special characters put into Byte array

I'm doing encrypt algotythm right now and I need to encrypt german words also. So I have to encrypt for example characters like: ü,ä or ö.

Inside I've got a function:

private static byte[] getBytesArray(string data)
{
    byte[] array;
    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
    array = asciiEncoding.GetBytes(data);            
    return array;
}

But when data is "ü", byte returned in array is 63 (so "?"). How can I return ü byte?

I also tried:

private static byte[] MyGetBytesArray(string data)
{
    byte[] array;
    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();

    Encoding enc = new UTF8Encoding(true, true);
    array = enc.GetBytes(data);

    return array;
}

but in this case I get 2 bytes in array: 195 and 188.

like image 669
Marshall Avatar asked Nov 05 '12 10:11

Marshall


2 Answers

Please replace System.Text.ASCIIEncoding with System.Text.UTF8Encoding and rename the encoding object accordingly in your first example. ASCII basically does not support german characters, so this is why you'll have to use some other encoding (UTF-8 seems to be the best idea here).

Please take a look here: ASCII Encoding and here: UTF-8 Encoding

like image 97
Piotr Justyna Avatar answered Oct 12 '22 22:10

Piotr Justyna


You can use this

System.Text.Encoding utf_8 = System.Text.Encoding.UTF8;

// This is our Unicode string:
string s_unicode = "abcéabc";

// Convert a string to utf-8 bytes.
byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(s_unicode);

// Convert utf-8 bytes to a string.
string s_unicode2 = System.Text.Encoding.UTF8.GetString(utf8Bytes);
like image 36
Shyam sundar shah Avatar answered Oct 12 '22 22:10

Shyam sundar shah