2013-03-06 82 views
2

我试图在bash(linux)中找到与C#代码相同的代码。bash代码中的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“

有什么想法?

+1

我想你应该发布文件中的一个片段,你想读 – 2013-03-06 09:47:53

+2

只是一个随机的想法:如果你有工作的C#代码 - 有你使用考虑单?这听起来像你正试图将其转换为bash:你试过了什么? – 2013-03-06 09:52:36

+0

+1给Marc的建议。另一个随意的想法是,如果你在Linux上运行,默认情况下你有许多编程语言的运行时,你不能在Windows上运行。你[可以用python真的很容易](http://stackoverflow.com/a/606199/969613),然后[从Bash运行Python脚本](http://stackoverflow.com/a/4377147/969613 )。只是一个想法! – JMK 2013-03-06 10:00:23

回答

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