i have this code to convert a number in base 2, but if i want to convert 2 i get 10, and should be 00000010 i think, so ho i can add for number in 1 Byte i made this, but for the rest? Code (CSharp): string binary = Convert.ToString(value, 2); if (binary.Length < 8) { int test2 = 8 - binary.Length; if (test2 == 7) { await ReplyAsync("0000000" + binary); } else if (test2 == 6) { await ReplyAsync("000000" + binary); } else if (test2 == 5) { await ReplyAsync("00000" + binary); } else if (test2 == 4) { await ReplyAsync("0000" + binary); } else if (test2 == 3) { await ReplyAsync("000" + binary); } else if (test2 == 2) { await ReplyAsync("00" + binary); } else if (test2 == 1) { await ReplyAsync("0" + binary); } } else if (binary.Length == 8) { await ReplyAsync(binary); } else if (binary.Length > 8) { await ReplyAsync(binary); }
What about just simply this: string binary = System.Convert.ToString(value, 2).PadLeft(8,'0'); That will convert to binary, then left pad with 0's to get up to 8 characters. Of course this will only work up to 255 though.. not sure what your exact needs are.
base 2 does not necessarily have the padded zero's. People just often write binary in words of 8 digits, because it's often done so in the context of memory, where 1 byte (8 bits) is often the smallest word size. @cstooch has it right on the money as well if you want it.
Thnaks, for help, at code i have this: Code (CSharp): if(value <= 255) { string binary = Convert.ToString(value, 2).PadLeft(8, '0'); await ReplyAsync(binary); } else if (value <= 65535) { string binary = Convert.ToString(value, 2).PadLeft(16, '0'); await ReplyAsync(binary); } else if (value <= 16777215) { string binary = Convert.ToString(value, 2).PadLeft(24, '0'); await ReplyAsync(binary); }