简体   繁体   中英

How to convert an int that is negative to a binary string reprezentation?

I know that to convert a number to a binary string is necessary to check the rest of the division of the number by 2 at each iteration, more precisely at each division by 2. For example:

public static string intToBinary(int n)
{
    String binary = "";
    while (n > 0)
    {
        binary =  ( (n % 2 ) == 0 ? "0" : "1") + binary;
        n = n / 2;
    }
    return binary;
}

If we had a negative number we would use the complementary code which would mean that the bits would be inverted and in the end 1 is added to the result.

In this case, how should it be done in the code to get the negative number in the binary?

Receive the sacred gifts offered by the Integer class. It offers a method that can convert an int to its binary string representation: Integer.toBinaryString(int i) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM