2

I`m trying to find equivalent code in bash (Linux) to 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?

Fred
  • 3,365
  • 4
  • 36
  • 57
gil kr
  • 2,190
  • 1
  • 17
  • 23
  • 1
    I think you should publish a short extract of your file that you're trying to read – Brian Agnew Mar 06 '13 at 09: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 06 '13 at 09: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](http://stackoverflow.com/a/606199/969613), and then [run the Python script from Bash](http://stackoverflow.com/a/4377147/969613). Just a thought! – JMK Mar 06 '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 06 '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 06 '13 at 10:02

2 Answers2

0

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
gil kr
  • 2,190
  • 1
  • 17
  • 23
0

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
Esailija
  • 138,174
  • 23
  • 272
  • 326