I have a number and I want to print it in binary. I don't want to do it by writing an algorithm, Is there any built-in function for that in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Old school:
The question is tricky in java (and probably also in other language).
A Integer is a 32-bit signed data type, but Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2.
So, Integer.parseInt(Integer.toBinaryString(X),2) can generate an exception (signed vs. unsigned).
The safe way is to use Integer.toString(X,2); this will generate something less elegant:
-11110100110
But it works!!!
Enter any decimal number as an input. After that we operations like modulo and division to convert the given input into binary number. Here is the source code of the Java Program to Convert Integer Values into Binary and the bits number of this binary for his decimal number. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
I think it's the simplest algorithm so far (for those who don't want to use built-in functions):
Example:
convertNumber(1) --> "0b1"
convertNumber(5) --> "0b101"
convertNumber(117) --> "0b1110101"
How it works: while-loop moves a-number to the right (replacing the last bit with second-to-last, etc), gets the last bit's value and puts it in StringBuilder, repeats until there are no bits left (that's when a=0).