c# - Convert stringbinary to ascii -
i'm started dev-ing app wp7 , i'm trying convert string of binary ascii using c#.
but have no idea how can done. hope me out here.
example :
input string: 0110100001100101011011000110110001101111
output string: hello
the simple solution,
using substring , built in convert.tobyte this:
string input = "0110100001100101011011000110110001101111"; int charcount = input.length / 8; var bytes = idx in enumerable.range(0, charcount) let str = input.substring(idx*8,8) select convert.tobyte(str,2); string result = encoding.ascii.getstring(bytes.toarray()); console.writeline(result);
another solution, doing calculations yourself:
i added in case wanted know how calculations should performed, rather method in framework you:
string input = "0110100001100101011011000110110001101111"; var chars = input.select((ch,idx) => new { ch, idx}); var parts = x in chars group x x.idx / 8 g select g.select(x => x.ch).toarray(); var bytes = parts.select(bitcharstobyte).toarray(); console.writeline(encoding.ascii.getstring(bytes));
where bitcharstobyte conversion char[] corresponding byte:
byte bitcharstobyte(char[] bits) { int result = 0; int m = 1; for(int = bits.length - 1 ; >= 0 ; i--) { result += m * (bits[i] - '0'); m*=2; } return (byte)result; }
both above solutions same thing: first group characters in groups of 8; take sub string, bits represented , calculate byte value. use ascii encoding convert bytes string.
Comments
Post a Comment