Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are integers cast to bytes in Java?

Tags:

I know Java doesn't allow unsigned types, so I was wondering how it casts an integer to a byte. Say I have an integer a with a value of 255 and I cast the integer to a byte. Is the value represented in the byte 11111111? In other words, is the value treated more as a signed 8 bit integer, or does it just directly copy the last 8 bits of the integer?

like image 392
LandonSchropp Avatar asked Mar 16 '10 22:03

LandonSchropp


People also ask

Can you cast an int into a byte Java?

The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).

Can int be type casted to byte?

@helixed: Yes, that's correct.

How does int casting work in Java?

In Java when you cast you are changing the “shape” (or type) of the variable. The casting operators (int) and (double) are used right next to a number or variable to create a temporary value converted to a different data type. For example, (double) 1/3 will give a double result instead of an int one.

Why integer is 4 bytes in Java?

The fact that an int uses a fixed number of bytes (such as 4) is a compiler/CPU efficiency and limitation, designed to make common integer operations fast and efficient.


1 Answers

This is called a narrowing primitive conversion. According to the spec:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

So it's the second option you listed (directly copying the last 8 bits).

I am unsure from your question whether or not you are aware of how signed integral values are represented, so just to be safe I'll point out that the byte value 1111 1111 is equal to -1 in the two's complement system (which Java uses).

like image 127
Michael Myers Avatar answered Oct 26 '22 23:10

Michael Myers