>>>>>>>string s = "0101000001000101010101000100010101010010" >>>>>>>>>>>>>>
>>>>>>if( string[stringindex] == '1' ) { >>>>>> the byte index = stringIndex / 8 >>>>>> the bit to set = 7 - (stringIndex %8), >>>>>> >>>>>> // you may have to cast the right hand side to (byte) >>>>>> >>>>>> byteArray[ stringIndex / 8] |= ( 1 << ( 7 - (stringIndex %8))) >>>>>> >>>>>> or maybe due to widening >>>>>> byteArray[ stringIndex / 8] = (byte)( byteArray[ stringIndex / 8] | byteArray[ stringIndex / 8] | ( 1 << ( 7 - (stringIndex %8)))) >>>>>>} >>>>>>>>>>>
static IEnumerable<char> GetChars(string s) >>> { >>> return Enumerable.Range(0, s.Length / 8).Select(i => >>> Convert.ToChar(Convert.ToInt32(s.Substring(i * 8, 8),2))); >>> }then
string result = string.Empty; >>>foreach (char c in GetChars(s1)) >>>{ >>> result += c; >>> }Nothing like making it complicated when simple would do :-}
>>using System; >>using System.Collections.Generic; >>using System.Linq; >>using System.Text; >>using System.Collections; >>namespace BinaryToText >>{ >> class Program >> { >> static void Main(string[] args) >> { >> // PETER KANE >> string binarytext = "01010000010001010101010001000101010100100010000001001011010000010100111001000101"; >> >> for (int i = 0; i < binarytext.Length; i+= 8) >> { >> Console.Write(Bin2Dec(binarytext.Substring(i, 8))); >> } >> >> Console.WriteLine(); >> } >> >> >> static char Bin2Dec(string binstr) >> { >> if(binstr.Trim().Length != 8) >> return ' '; >> >> int retval = 0; >> int len = binstr.Length - 1 ; >> >> for (int i = 0; i <= binstr.Length - 1; i++) >> if (binstr[len - i] == '1') >> retval += (int)Math.Pow((double)2, (double)i); >> >> return((char)retval); >> } >> } >>} >> >>>Coffee break. Here's a method to do the reverse:
static string ConvertToBinaryString(string s) > { > char[] input = s.Reverse().ToArray(); > char[] output = new char[input.Length * 8]; > int pos = output.Length - 1; > for (int i = 0; i < input.Length; i++) > { > for (byte i2 = 0; i2 < 8; i2++) > output[pos--] = (input[i] & (1 << i2)) != 0 ? '1' : '0'; > } > return new string(output); > }You're showing off now bitshifting - maybe we should start a weekly competition for this sort of stuff - bit of light relief really and making us blow the dust off our brains - thanks again