Reputation: 6275
I am learning about bits and how memory stores integers and other datatypes. I know that int a = 11
will be stored in memory as bits as 1011
. How will String b = "11"
be stored as bits.
Upvotes: 2
Views: 1648
Reputation: 853
public static void main(String[] args) {
for(final byte b : "11".getBytes()) {
String asBinary = String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
System.out.print(asBinary);
}
}
Upvotes: 1
Reputation: 9001
Actually, an int on most machines is stored as
00000000000000000000000000001011
It will always use the word size on the language/machine (or 32 bits in most cases).
A string is an object. it has a variety of properties and the implementation can vary a lot between languages. For the main portion, the actual string data, there are two fairly typical ways of storing it: storing length separately, or null termination.
Either way it determines the length, the characters are stored as a sequence of bytes. The size of each character depends on language/compiler settings, etc. In order to support non-english languages and special characters, it is common to store 16bits per character, but older languages often still use 8.
character encoding is based off the old ASCII table, but newer specifications cover a lot more. Check out UTF-8 and UTF-16.
But, for just understanding the basics, the ASCII table gives us somewhere to go. Each character in the string is defined by a number, and then that number is encoded in binary, just like an int.
The character "1" is represented by the ASCII code 49 (decimal), which in binary is 00110001. The entire string may look like:
001100010011000100000000
including a null terminator.
Upvotes: 1