Adding binary numbers

后端 未结 21 1525
孤独总比滥情好
孤独总比滥情好 2020-11-28 07:50

Does anyone know how to add 2 binary numbers, entered as binary, in Java?

For example, 1010 + 10 = 1100.

21条回答
  •  孤街浪徒
    2020-11-28 08:05

    You can just put 0b in front of the binary number to specify that it is binary.

    For this example, you can simply do:

    Integer.toString(0b1010 + 0b10, 2);
    

    This will add the two in binary, and Integer.toString() with 2 as the second parameter converts it back to binary.

提交回复
热议问题