问题
So I am quite new to Java and motivated to learn. This question might seem simple but I genuinely don't understand and have searched Google for answers (no luck).
I am converting a decimal into Binary in Java. However, I thought representations of numbers are supposed to be given in data types int
, double
, and etc.
The code is as follows :
int decimal = 99;
String binary = Integer.toBinaryString(decimal);
System.out.println(binary);
Why is it String binary
, should it not be any of the numerical data types?
回答1:
Internally, all values are stored as binary values. Because it's easier to read, integers are converted into digits for display. Displaying a value as a binary is thus purely a representation issue.
So 99 is internally stored as 01100011. You can display it as a hexadecimal (0x63), a decimal (99), or a binary. But because the numerical value is the same in each case, the only difference is the symbols used to display it, and this symbolic representation is as a String.
回答2:
The following int
s are all equal:
int i = 99;
int j = 0o143;
int k = 0x63;
int l = 0b1100011;
If you want to print them, you have to convert them to a String
using a utility method of Integer
, or you use number formatting.
来源:https://stackoverflow.com/questions/61320962/why-is-binary-represented-as-a-string