我如何转换string为byte[]在.NET(C#),而无需手动指定一个特定的编码?
我要加密字符串.我可以在不转换的情况下加密它,但我仍然想知道为什么编码在这里发挥作用.
另外,为什么要考虑编码?我不能简单地得到字符串存储的字节数吗?为什么依赖于字符编码?
我有一个byte[]从我碰巧知道包含UTF-8的文件加载的数组.在一些调试代码中,我需要将其转换为字符串.有没有一个班轮可以做到这一点?
在封面下它应该只是一个分配和一个memcopy,所以即使它没有实现,它应该是可能的.
本质上,string使用UTF-16字符编码形式
但是当与StreamWriter保存时:
此构造函数创建一个StreamWriter,其UTF-8编码没有字节顺序标记(BOM),
我见过这个样本(删除了断开的链接):

utf8对于某些字符串看起来更小,而utf-16在其他字符串中则更小.
utf16在utf8保存文件时使用字符串的默认编码?谢谢.
ps我已经读过这篇着名的文章了
我对字符编码的概念很困惑.
什么是Unicode,GBK等?编程语言如何使用它们?
我需要打扰他们吗?是否有更简单或更快速的编程方式,而不必麻烦自己?
是否有一种简单的方法将字节数组转换为字符串,以便下面的单元测试通过?我找不到适用于所有值的编码.
[TestMethod]
public void TestBytToString()
{
byte[] bytArray = new byte[256];
for (int i = 0; i < bytArray.Length; i++)
{
bytArray[i] = (byte)i;
}
string x = System.Text.Encoding.Default.GetString(bytArray);
for (int i = 0; i < x.Length; i++)
{
int y = (int)x[i];
Assert.AreEqual(i, y);
}
}
Run Code Online (Sandbox Code Playgroud) 可能重复:
c#中的byte []到字符串
我有一个从流中读取的字节数组.我想将它转换为字符串.
这对我有用:
var str= new string(bytearr.Select(x=>(char)x).ToArray());
Run Code Online (Sandbox Code Playgroud)
但我觉得有更好的方法吗?在那儿?
使用以下函数:http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
public static byte[] encryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
Run Code Online (Sandbox Code Playgroud)
如您所见,它返回一个字节数组,我想将字节数组转换为字符串.
如何将它从字节数组转换为字符串,反之亦然?
我在dotnet核心中散列字符串时得到奇怪的结果我发现了类似的问题:用ASP.NET Core计算SHA1 并找到了如何在.net核心中将字节数组转换为字符串
这是我的代码:
private static string CalculateSha1(string text)
{
var enc = Encoding.GetEncoding(65001); // utf-8 code page
byte[] buffer = enc.GetBytes(text);
var sha1 = System.Security.Cryptography.SHA1.Create();
var hash = sha1.ComputeHash(buffer);
return enc.GetString(hash);
}
Run Code Online (Sandbox Code Playgroud)
这是我的考验:
string test = "broodjepoep"; // forgive me
string shouldBe = "b2bc870e4ddf0e15486effd19026def2c8a54753"; // according to http://www.sha1-online.com/
string wouldBe = CalculateSha1(test);
System.Diagnostics.Debug.Assert(shouldBe.Equals(wouldBe));
Run Code Online (Sandbox Code Playgroud)
输出:
MHnѐ&ȥGS
我安装了nuget包System.Security.Cryptography.Algorithms(v 4.3.0)
还试图GetEncoding(0)获得sys默认编码.也没工作.
c# ×7
string ×4
.net ×3
.net-core ×1
aes ×1
arrays ×1
asp.net-core ×1
byte ×1
bytearray ×1
cryptography ×1
encoding ×1
encryption ×1
sha1 ×1
utf-16 ×1
utf-8 ×1