Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I`m trying to find equivalent code in bash (linux) to a C# code.

I have this C# code:

// 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);

I'm running bash on fedora linux machine.

I`m getting in bash a file containg all the byte array as text seperated by whitespace like this:

"72 0 101 0 108 0 108 0 111 0 32 0 87 0 111 0 114 0 108 0 100 0 33 0"

any ideas?

share|improve this question
1  
I think you should publish a short extract of your file that you're trying to read –  Brian Agnew Mar 6 '13 at 9:47
2  
Just a random thought: if you have C# code that is working - have you considered using Mono? It sounds like you are trying to convert this to bash: what have you tried? –  Marc Gravell Mar 6 '13 at 9:52
    
+1 to Marc's suggestion. Another random thought, if you are running on Linux, you have the runtimes for a number of programming languages by default, that you don't get with Windows. You could do this really easily with python, and then run the Python script from Bash. Just a thought! –  JMK Mar 6 '13 at 10:00
    
i already have a script in bash and i need to add another function to it that can do this –  gil kr Mar 6 '13 at 10:00
    
I suppose python could work, i tried to avoid it so the entire code will be in one script but if there is no way to accomplish this in bash... –  gil kr Mar 6 '13 at 10:02

2 Answers 2

Those bytes are in UTF-16LE encoding, not UTF-8. Your python script should just be:

file = codecs.open('xx.txt', 'r', 'utf-16-le')
ustring = file.read() #this is a unicode string, not a normal python string
print ustring
share|improve this answer

Eventually i did it in python and called the python script from my bash script:

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.