Why is Binary represented as a String?

我只是一个虾纸丫 提交于 2021-02-05 07:12:07

问题


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 ints 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!