0

For example we have

string in_decimal = "50";

What is the best way to make a string that holds that number in binary? The best I've come up with is:

string in_binary = Convert.ToString(Convert.ToUInt32(in_decimal), 2);

While this works it feels silly to have to convert it to an integer and back. Is there a better way of going about this?

burritab
  • 25
  • 4
  • I doubt it. Knowing the length of the string you could process the decimal string a digit at a time, and then do an arithmetic-encoding-like generation of each binary digit you can at that point, knowing an upper bound and a lower bound of the number to come, but I don't think that's worth it. – Rup Jul 23 '19 at 15:20
  • 5
    Possible duplicate of [Convert integer to binary in C#](https://stackoverflow.com/questions/2954962/convert-integer-to-binary-in-c-sharp) – Heretic Monkey Jul 23 '19 at 15:21
  • 1
    Well, I'd say "welcome to the world of `type safety`" - I believe there is no way around than to `Convert` your `String` to an `Int` first. – Rand Random Jul 23 '19 at 15:21
  • 7
    There's nothing silly about it, really. You can't *directly* convert the characters `5` and `0` into the binary representation of the base 10 number they represent because 10 is not a power of 2. – Jeroen Mostert Jul 23 '19 at 15:22
  • 2
    It's not silly. Before you can perform mathematical operations on a number, you need a *number*. –  Jul 23 '19 at 15:43
  • 1
    You ask for the "best" solution and a "better" solution without saying what your metric is for betterness or bestness other than "not making me feel silly". We don't know what does or does not make you feel silly. – Eric Lippert Jul 23 '19 at 17:35

0 Answers0