[Java] details of converting int to byte

Posted by lauthiamkok on Wed, 05 Jan 2022 05:39:16 +0100

1. Preface

I have two years of Java development experience. During the development period, I mostly did CRUD work, boiling frogs in warm water. I've been thinking about investing in my resume recently. I'll see what the market is outside. I've also memorized some eight part essays in my spare time. I met a family last week. Although the contents of the questions were very basic, they were just questions that would be asked by college students who had just graduated. As a result, I was too nervous, my mind was blank, I forgot some questions, and was hung up by the interviewer.....

Learn from the bitter experience. From now on, record the questions asked by each interviewer (if you remember), Chong!

2. Problems

Interviewer: give you 255 of type int, assign it to a variable of type byte, and then print this variable. What is the result?

Me: 255

Interviewer: what is the range of byte s?

Me: let me see (two minutes have passed)....

Interviewer: OK, let me change another question......

In fact, before the interview, I specially wrote down the number of bytes of each basic type, but I didn't answer the above questions.

Don't say much, just go to the code:

public class TestCase {

public static void main(String[] args) {
int a = 255;
byte b;
b = (byte)a;
System.out.println(b);

System.out.println(Integer.toBinaryString(a));
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
}

}

Output:

-1
11111111
-128
127

You can see that the result is [- 1], but how does this result come from?

3.1 technical preparation

First, back to a basic question, what is the range of byte s in java?

As can be seen from the above print results, the range of byte type is [- 128127].

How did this [- 128 ~ 127] come from?

This again involves the memory size occupied by each integer type in java.

The number of bytes in java takes up 1 byte.

A byte = 8 bits, and a bit is a 0 or 1.

What is the concept of bit? One is what we often call 1bit. 1bit is a 0 or 1. As we all know, computers only know 0 and 1.

A bit can be imagined as a small bulb. When the bulb is on, it is 1, when it is not on, it is 0, and a byte is 8 small bulbs arranged together.

Therefore, a byte variable with a size of one byte is represented by 8 bits (8 small bulbs).

So what do these eight mean? How to use 8 bits to represent a number?

First of all, we should understand how binary numbers are converted into decimal numbers. We can find them on Baidu online. It will not be described here.

How do you actually describe a number in binary in java and even in the computer?

We all stand on the shoulders of giants. How to use 8 bits to represent a number has been arranged by computer pioneers decades ago. The answer is to use something called [complement]. What's the complement??

It's hard to explain. Go directly to the link:

In depth understanding and principle of original code, inverse code and complement code_ Xiaoyunlu blog - CSDN blog_ Inverse complement of original code

3.2 start calculation

After making up the above content, we can first understand why the byte range is [- 128127], and then we can finally start to study why 255 of int becomes - 1 after it is converted to byte.

In java, int is 4 bytes, that is, 4 groups of small bulbs with 8 bulbs in each group.

255 of int type is represented by binary (it is also printed in the above demonstration program, but only the last 8 1s are printed because the high bits are 0). It is as follows (the high bits are on the left):

00000000 00000000 00000000 11111111

While byte has only one byte, only one row of small bulbs can be used. int has four rows and can't fit. What should we do?

Therefore, the three high-order bytes are discarded and the low-order row is used to represent byte, as shown in the following figure:

11111111

Well, now as long as we translate these 8 1s into familiar decimal numbers, it's OK.

The translation process is a process of finding the original code according to the complement, as follows:

First of all, you should know that this is a [complement]. First look at the first bit (sign bit). The first bit is 1, indicating that this is a negative number.

Then, since it's a negative number, ignore the first 1

First invert (i.e. 0 becomes 1, 1 becomes 0) the next 7 bits, then the next 7 bits will be inverted and become 7 0: 0000000

Then, the inverted binary number + 1 becomes 6 zeros plus 1: 0000001

Therefore, the original code obtained by adding the previous first 1 is 

That is [- 1].

3.3 revalidation

Well, now I'm looking for a random number and calculate it manually. Let's find 278 of int type

The binary complement of 278 of type int represents:

public class TestCase {

public static void main(String[] args) {
int a = 278;
byte b;
b = (byte)a;
//        System.out.println(b);

System.out.println(Integer.toBinaryString(a));
}

}

Output:
100010110

Namely:
00000000 00000000 00000001 00010110

Look at the last 8 digits:

00010110

The first is 0. Hey, it's a positive number. The [complement] of the integer is the same as the [original code], which should be 2 + 4 + 16 = 22

Verify:

public class TestCase {

public static void main(String[] args) {
int a = 278;
byte b;
b = (byte)a;
System.out.println(b);

System.out.println(Integer.toBinaryString(a));
}
}

Output:
22
100010110

Sure enough, 22, the calculation is correct!

OK, strike while the iron is hot. Another one, calculate 128 of int type and assign it to byte type.

public class TestCase {

public static void main(String[] args) {
int a = 128;
System.out.println(Integer.toBinaryString(a));
byte b;
b = (byte)a;
System.out.println(b);
}
}

Output:
10000000
-128

First, let's look at the binary representation of int:

00000000 00000000 00000000 10000000

Binary converted to byte:

10000000

Hey, look at the first place. It's a 1, a negative number,

Invert the following seven zeros to seven ones. When seven ones add one, they become one 1 and seven zeros:

1111111 + 0000001 = 10000000

In combination with the first 1, the original code obtained is:

110000000

That is - 1 times 2 to the 7th power = - 128

OK, another negative int, calculate - 130 of int type and assign it to byte type.

public class TestCase {

public static void main(String[] args) {
int a = -130;
System.out.println(Integer.toBinaryString(a));
byte b;
b = (byte)a;
System.out.println(b);
}
}
Output:
11111111111111111111111101111110
126

Binary of int:

11111111 11111111 11111111 01111110

Binary of byte:

01111110

First of all, the first is a 0, which is a positive number. There is no need to take the inverse. Just add it by bit, 2 + 4 + 8 + 16 + 32 + 64 = 126

So it's 126

4. Simple solution

Make sense, it's OK to manually calculate decimal from binary. You're making trouble for me, fat tiger!

In fact, int corresponds to the part within the byte range. Once the value of int exceeds the byte range, you can cycle from another boundary of byte:

128 is the first number that exceeds the maximum value of byte, so it starts from the minimum value of byte, that is, - 128 after 128 of int is converted to byte,

Similarly, the conversion of 129 of int to byte is - 127, and so on.

The same is true for the lower number. After - 128 of int is converted to byte, it is - 128, while - 129 of int is converted to byte, it is 127.

Therefore, the compatibility between a large range and a small range of numbers is regular. Take int and byte for example, the last 8 bits are always a cycle:

For example, 0 of int:

int :00000000 00000000 00000000 00000000
byte:                           00000000

For example, 1 of int:

int :00000000 00000000 00000000 00000001
byte:                           00000001

...

For example, 127 of int:

int :00000000 00000000 00000000 01111111
byte:                           01111111

For example, 128 of int:

int :00000000 00000000 00000000 10000000
byte:                           10000000  // -128

For example, 255 of int:

int :00000000 00000000 00000000 11111111
byte:                           11111111 // -1

For example, 256 of int:

int :00000000 00000000 00000001 00000000
byte:                           00000000  // 0

Topics: Java