如何在bash代码Linux中将字节数组转换为字符串

问题描述 投票:2回答:2

我正在尝试在bash(Linux)中找到与C#代码等效的代码。

我有这个C#代码:

// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
str = enc.GetString(dBytes);

我正在fedora Linux计算机上运行bash。

我正在bash中将包含所有字节数组的文件作为文本,并用空格分隔,如下所示:

“” 72 0 101 0 108 0 108 0 111 0 32 0 87 0 111 0 114 0 108 0 100 0 33 0“

任何想法?

c# linux bash encoding byte
2个回答
0
投票

最终我在python中完成了此操作,并从我的bash脚本中调用了python脚本:

file = open('xx.txt', 'r')
inputText = file.read()
split = inputText.split(" ")
noZeros= filter (lambda a: a != "0", split)
results = map(int, noZeros)
final = "".join(map(chr, results))
print final

0
投票

这些字节采用UTF-16LE编码,而不是UTF-8。您的python脚本应该只是:

file = codecs.open('xx.txt', 'r', 'utf-16-le')
ustring = file.read() #this is a unicode string, not a normal python string
print ustring
© www.soinside.com 2019 - 2024. All rights reserved.