JavaRush /Java Blog /Random EN /Java: bits and bytes
Viacheslav
Level 3

Java: bits and bytes

Published in the Random EN group
Java: bits and bytes - 1

Introduction

If people count in the decimal number system, then computers count in the binary system. And a programmer must understand how to talk to both people and computers. This review should help in this matter. Sometimes there is a whole world hidden behind the obvious. I propose to talk about this world. For example, there are 7 days in a week. Now, let’s answer the question: What is the number “7”? ) Firstly, it is an integer (positive) natural number. It is also a decimal number. A decimal number is a number in the Decimal System. When we say "decimal number system", it means that the number system has a base of 10 . The radix shows how many digits can be used in a given number system to represent a number. The countdown is from zero. Accordingly, to represent numbers in the decimal number system, we use numbers from 0 to 9. This is good, but we need to count not only to 9, but also beyond. How to be? For example, the number 10. To write this number, we use as many as 2 digits. The position of each digit in the decimal system is called decimal place. The digits are counted from right to left:
Java: bits and bytes - 2
In addition, the decimal number can be expanded as follows: 103 = 1*10^2 + 0*10^1 + 3*10^0
Java: bits and bytes - 3
The number essentially grows from right to left. That is, at first it was 7, and then it became 10. Therefore, the digits are counted from the right, starting from zero. What is all this for? This is because we are not computers. And while we count in decimal (that is, base 10), computers count in binary (that is, base 2). But the rules that apply in these number systems are the same.
Java: bits and bytes - 4

Binary system

The binary system is very similar to the decimal system, with the only difference being that the limit here is not 10, but 2. Let's compare with an example. How do we represent 11 in binary? It’s very simple: you just need to divide the decimal number by base 2, that is, count 11/2 in a column. Example:
Java: bits and bytes - 5
Or here's an example from WikiHow:
Java: bits and bytes - 6
Interestingly, we can represent a number in binary the same way as in decimal: 111 in binary = 1*2^2 + 1*2^1 + 1*2^0 = 4 + 2 + 1
Java: bits and bytes - 7
An example of conversion from binary to decimal can be seen in the online calculator . Speaking about the fact that the rules of operation in number systems are the same, let's look at addition in the binary system:
Java: bits and bytes - 8
As you can see, we transfer digits during addition in the same way as in the decimal system. Analysis of addition can be seen, for example, here: By the way, some word “discharge” is periodically mentioned. And what is it? Place is just a “structural element” of representing a number. That is, the number 10 consists of two digits: we need 2 digits, 2 places, 2 elements to write this number. It is important for us to understand this because in the binary number system, a digit is a bit . The word Bit comes from the English "binary digit" , that is, a binary number. It can be either 0 or 1. But just as we read numbers and words as a whole, and not letter by letter, computers do not read one bit at a time. For the minimum “piece” of processed information in RAM (the so-called smallest addressable unit of information), a sequence of 8 bits is read . Since there are 8 of them, this one is called an "octet". And also - the more well-known word Byte . To remember the octet, you can remember that the word octopus (eight legs) is translated into English as octopus. That is, here is exactly the same “octo” in the title:
Java: bits and bytes - 9
Let's think about what is the maximum number we can represent as 8 bits?
Java: bits and bytes - 10
And here the question arises: what about negative numbers? To understand this, let's talk about how bytes are represented in Java
Java: bits and bytes - 11

Java and Byte

How is it that we can use negative numbers in Java? It's done simply. In Java, bytes are signed. The leftmost digit/bit (also called the “most significant bit”) is made a kind of “marker” that answers the question: “Is this number negative?” If the answer is yes, then the marker has the value 1. Otherwise, it is 0. Let's look at an example of how to turn the number 5 into a negative number 5:
Java: bits and bytes - 12
Based on this picture, you can understand the limits within which a Byte value lies:
Java: bits and bytes - 13
It is also clear that:
  • if we add one to 127, we get -128.
  • if we subtract one from -128, we get 127.
Thus, Byte in Java can take a value from -128 to 127. As we remember, a byte is an octet. And the maximum digit/most significant bit has a serial number of 7, since we count from zero. In this case, it is easy to remember that a byte is equal to -2 to the power of 7 (lower limit) to 2 to the power of 7 minus 1 (upper limit). Working with the data type itself is simple. We use the online Java compiler “repl.it” as a “sandbox” for this article. https://repl.it/languages/java. For example, let's run the code that will represent a byte variable in binary form as a string:
class Main {
  public static void main(String[] args) {
    byte octet = 5;
    String bin = String.format("%8s", Integer.toBinaryString(octet)).replace(' ', '0');
    System.out.println(bin);
  }
}
Working with bytes is actively used when working with I/O Streams. You can read more in the tutorial from Oracle: " I/O Streams ". In addition, in Java you can use a special literal to specify the value as bits:
class Main {
  public static void main(String[] args) {
    byte data = 0b101;
    System.out.println(data);
  }
}
Java: bits and bytes - 14

Bit Manipulation

Touching on bytes and bits, one cannot fail to mention various bit manipulations. Probably the most common operation is shifts (bitwise shift or bit-shift). And all because their result has clear practical benefits. What's the use? Shifting left by N positions is equivalent to multiplying the number by 2N. And a shift to the right is similar to the same division. Thus, 5<<2 == 5*Math.pow(2,2) And to understand why this is so, let's look at this example in more detail:
Java: bits and bytes - 15
The bitwise negation NOT (Unary bitwise), which is represented by a tilde, inverts the bits. It is written as a tilde, for example ~5.
public static void main(String[] args) {
	System.out.println(~5); //-6
 	System.out.println(~-5);//4
}
This once again shows that when Java changes the sign of a number, in addition to inverting the bit values ​​at the very end, we perform +1. And without this, as we see, our number 5 changes. And so that it remains the same number as before changing the sign, you need to do +1. Bitwise AND allows you to leave two different numbers with the value 1 for a bit only if all bits have a value of one. What's interesting about this may be that it has some application benefits:
int x=4;
System.out.println((x&1) != 1);
This code checks the number x for parity. Let's look at an example:
Java: bits and bytes - 16
By using Bitwise AND and Bitwise OR together, you can use masks:
public static void main(String[] args) {
    byte optionA=0b0100;
    byte optionB=0b0010;
    byte optionC=0b0001;
    byte value = (byte)(optionB | optionC);
    // Check for optionB
    if ((optionC & value) != 0b0000) {
      System.out.println("Yes");
    } else {
      System.out.println("No");
    }
  }
See " Masking options with bitwise operators in Java " for more details . Bit manipulation is an interesting topic on which separate reviews, articles and books have been written. And from here begins the long path to cryptography. As part of this review, it is worth understanding why it works and how. For more information about bit operations, I recommend reading the review from tproger: “ About bit operations .”

Primitive types

So, a byte is an octet, that is, 8 bits. It’s easy to remember that in Java there are also 8 primitive types, coincidentally. A primitive type is a data type that is built into a programming language, that is, available by default. byte is the smallest primitive data type in terms of memory footprint that Java can work with. As we said earlier, a byte takes up 8 bits. Therefore, the most significant digit is number 7. Therefore, byte contains the values ​​from -2 to the 7th power to 2 to the 7th power minus 1 of the result. What other primitive types are there:
Java: bits and bytes - 17
As we can see from the table, data types in terms of the amount of data occupied doubles. That is, short = 2 * byte, and int = 2 * short. It's actually easy to remember. Remember that byte = 8 bits. The fact that it cannot be less is also remembered. In English, an integer is called an integer. The primitive type from it was called the abbreviation int. There is a regular integer - int. There is a short version, short, and a long version, long. Accordingly, int occupies 32 bits (4 bytes). The short version is 2 times smaller - 16 bits (2 bytes), and the long version is twice as large, i.e. 64 bits (8 bytes). So an int can at most store a number of about 2 billion and a hundred million. And long can store a maximum of about 9 quadrillion (a nice word). Remembering the old joke about how a novice programmer thinks that there are 1000 bytes in a kilobyte, and a complete programmer believes that there are 1024 grams in a kilogram, we can understand:
1 mb = 1024 Kbyte = 1024 * 1024 = 1048576 bytes
1 int = 4 bytes
1 mb = 262144 int
By the way, an attentive reader might have noticed that there are only 7 types in the picture. 8 primitive type is boolean. boolean is a Boolean data type that has only two values: true and false. But the question arises - what size is it? The Java Virtual Machine Specifiaction and section " 2.3.4. The boolean Type " will answer us:
Java: bits and bytes - 18
That is, just a boolean will take the same amount as an int. If we declare an array of boolean, then each element of the array will occupy 1 byte. These are such miracles :)

Conclusion

I suggest you familiarize yourself with a couple more materials to consolidate: #Viacheslav
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION