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

本文关键字:字节数 字节 数组 转换 字符串 bash 代码 Linux | 更新日期: 2023-09-27 18:02:35

我正在尝试在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"

任何想法?

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

最后我用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

这些字节采用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