How to convert integer to binary string in C#?

前端 未结 8 1994
失恋的感觉
失恋的感觉 2020-12-02 01:48

I\'m writing a number converter. How can I convert a integer to a binary string in C# WITHOUT using built-in functions (Convert.ToString does different things b

8条回答
  •  攒了一身酷
    2020-12-02 02:27

    You can construct the representations digit by digit from first principles.

    Not sure what built-in functions you don't want to use, but presumably you can construct a string character by character?

    1. Start with the highest power of two greater than the number.
    2. Push a "1" into your string.
    3. Subtract that power of two from your number.
    4. Take the next-lowest power of two. If you've reached one-half, stop. You're done.
    5. If the number that's left is greater than this power of two, go back to step 2. If not, push a "0" into the string and go back to step 4.

    For one's complement and two's complement, calculate those with an additional step.

    Or is this way too basic for what you need?

提交回复
热议问题