将德语特殊字符放入字节数组中

5

我现在正在进行加密算法,需要加密包括德语在内的单词。所以我必须加密例如:ü,ä或ö这样的字符。

我有一个函数:

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

当数据是“ü”时,返回数组中的字节为63(因此是“?”)。如何返回ü字节?
我还尝试过:
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;
}

但是在这种情况下,我得到数组中的2个字节:195和188。


1
在编码和解码中,使用UTF8Encoding而不是ASCIIEncoding - L.B
ASCII 的定义只能到 7Fh,而德语字符在 7Fh 之上(请验证)。你可以尝试使用 Encoding.Default 吗? - Angshuman Agarwal
@AngshumanAgarwal Encoding.Default 总是一个不好的选择,因为它是机器特定的。 - Marc Gravell
1
@Marshall 是的,在数组中获取该字符返回2个字节是完全符合预期的。如果你去掉 asciiEncoding(它没有被使用),你的第二个例子就可以工作了。个人建议直接使用 return Encoding.UTF8.GetBytes(data);,但本质上是一样的。你期望得到什么值?为什么? - Marc Gravell
@t3hn00b 代码页总是一个糟糕的妥协 - 特殊字符的范围即使在最合适的情况下也非常有限。像UTF-8这样的编码方式更可取。 - Marc Gravell
显示剩余3条评论
2个回答

7
请在第一个示例中将System.Text.ASCIIEncoding替换为System.Text.UTF8Encoding并相应更改编码对象的名称。ASCII基本上不支持德语字符,因此您需要使用其他编码(UTF-8似乎是最好的选择)。请参考这里:ASCII编码和这里:UTF-8编码

1
你可以使用这个。
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接