我有一个JSON格式的对象,字节数组以字符串形式出现。我需要将该字符串更改为字节数组,但不转换字符串。
static byte[] GetBytes(string str)
{
return str.Select(Convert.ToByte).ToArray();
}
上面的代码解决了这个问题,不幸的是它仍然将每个char转换为它的相应字节。
对于完整性,这是我的字符串
"PCFET0NUWVBFIGh0bWwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMDEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvVFIvaHRtbDQvc3RyaWN0LmR0ZCI+PGh0bWw+PGhlYWQ+PE1FVEEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTE2Ij48dGl0bGU+Q2l2aWwgUHJvY2VkdXJlIGluIE1hZ2lzdHJhdGVzJyBDb3VydHM8L3RpdGxlPjxsaW5rIHR5cGU9InRleHQvY3NzIiByZWw9InN0eWxlc2hlZXQiIGhyZWY9Ii4uL1N0eWxlcy9CV0NvbW1vbi5jc3MiPjxsaW5rIHR5cGU9InRleHQvY3NzIiByZWw9InN0eWxlc2hlZXQiIGhyZWY9Ii4uL1N0eWxlcy9TaXRlQ29tbW9uLmNzcyI+PHNjcmlwdCB0eXBlPSJ0ZXh0L2phdmFzY3JpcHQiIHNyYz0iLi4vc2NyaXB0cy9qcXVlcnktMS42LjIubWluLmpzIj48L3NjcmlwdD48c2NyaXB0IHR5cGU9InRleHQvamF2YXNjcmlwdCIgc3JjPSIuLi9zY3JpcHRzL3BvcHVwLmpzIj48L3NjcmlwdD48c2NyaXB0IHR5cGU9InRleHQvamF2YXNjcmlwdCIgc3JjPSIuLi9zY3JpcHRzL2hvdmVyYm94LmpzIj48L3NjcmlwdD48c2NyaXB0IHR5cGU9InRleHQvamF2YXNjcmlwdCIgc3JjPSIuLi9TY3JpcHRzL2pxdWVyeS5wcmludEVsZW1lbnQuanMiPjwvc2NyaXB0PjwvaGVhZD48Ym9keSBvbmxvYWQ9ImlmKHBhcmVudC5zZ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hIE5ldWtpcmNoZXIsIEFkdm9jYXRlIG9mIHRoZSBIaWdoIENvdXJ0LCBNZW1iZXIgb2YgdGhlIFByZXRvcmlhIEJhcjsgSkEgRmFyaXMsIFByb2Zlc3NvciBvZiBMYXcsIFVuaXZlcnNpdHkgb2YgU291dGggQWZyaWNhPGJyPjxiPkxhc3QgVXBkYXRlZDogPC9iPk9jdG9iZXIgMjAxMyAtIFNJIDMyLiBQcm9kdWN0IGRldmVsb3BlcjogQ3JhaWdlbiBTdXJhamxhbGw8L3A+PHA+PGJyPjxicj48L3A+PHA+PGJyPjxicj48L3A+PC9kaXY+PGRpdiBpZD0iY29udGV4dE1lbnUiPjwvZGl2PjwvYm9keT48c2NyaXB0IHR5cGU9InRleHQvamF2YXNjcmlwdCI+dHJ5e3dpbmRvdy5wYXJlbnQuc2V0RnJhbWVIZWlnaHQoIE1hdGgubWF4KE1hdGgubWF4KGRvY3VtZW50LmJvZHkuc2Nyb2xsSGVpZ2h0LCBkb2N1bWVudC5kb2N1bWVudEVsZW1lbnQuc2Nyb2xsSGVpZ2h0KSwgTWF0aC5tYXgoZG9jdW1lbnQuYm9keS5vZmZzZXRIZWlnaHQsIGRvY3VtZW50LmRvY3VtZW50RWxlbWVudC5vZmZzZXRIZWlnaHQpLCBNYXRoLm1heChkb2N1bWVudC5ib2R5LmNsaWVudEhlaWdodCwgZG9jdW1lbnQuZG9jdW1lbnRFbGVtZW50LmNsaWVudEhlaWdodCkpKTt9Y2F0Y2goZSl7fTwvc2NyaXB0PjwvaHRtbD4="
我需要将其更改为字节数组,例如
['P','C','F']等,没有将每个字符转换为它的相应字节
在该问题中,正在转换字符串。 标题中我不想转换
答案 0 :(得分:1)
假设这是您的实际问题描述:
我有一个base64编码的字符串,我希望将其转换为字节数组,其中每个字节包含base64字符串中一个字符的ASCII代码。
然后你可以很容易地做到这一点:
byte[] characterBytes = Encoding.ASCII.GetBytes(input);
因为base64字符串中使用的字符都低于Unciode代码点127,所以它们都可以用Encoding.ASCII获得的单个字节表示。
事实上,如果这是您的实际问题描述,则表明此问题与C# Convert a string to ASCII bytes重复。