Integer Wrapper Class [duplicate] - java

This question already has an answer here:
Understanding narrowing primitive conversion
(1 answer)
Closed 1 year ago.
Integer Wrapper class
Integer obj = new Integer("1000");
System.out.println(obj.byteValue( )); //-24
I am not able to understand that how this output is formed. I want to understand how this "1000" in an integer is converted into "-24" in a byte. I want to know about the logic behind this.

The docs say:
Returns the value of this Integer as a byte after a narrowing primitive conversion.
which isn't particularly helpful if you don't know what a "narrowing primitive conversion" is. Well, you can look into the Java Language Specification (section 5.1.3) for the definition of that:
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.
The Integer 1000 is represented by 32 bits:
00000000 00000000 00000011 11101000
byte is 8 bits, so we discard all but the 8 lowest order bits, we get:
11101000
which is -24 in 8-bit two's complement binary. -24 = -128 + 64 + 32 + 8

Casting an integer to a byte will give the last 8 bits of of the integer.
1000 in decimal -> 1111101000 in binary
Converting this to a byte value gives you 11101000 which is -24.

Related

Why does 0b1111_1111 cause a compiler error "int cannot be converted to byte" but not 0b111_1111? [duplicate]

This question already has answers here:
Understanding Java data types
(2 answers)
How to represent 11111111 as a byte in java
(2 answers)
JAVA: why binary literal for byte with negative sign is being considered as integer type?
(5 answers)
Closed 1 year ago.
byte b = 0b1111_1111;
byte c = 0b111_1111;
byte d = 0b0111_1111;
The first line causes a compilation error: incompatible types. I also tried 0xFF and decimal, the same. Thanks.
And I think byte means cannot be larger than what 8 bits hold. 0b1111_1111 is 8 bits.
All basic integer types in Java are signed. To be exact, byte, short, int and long are signed big endian two complement integers. That means that they run from - 2n-1 to 2n-1 - 1 where n is the number of bits - 8 for a byte (Byte.SIZE in Java), and therefore the range is from -128 to 127.
The number you are using is always an integer; number literals always are. However, the integer is actually the value 0x000000FF in hexadecimals. That cannot be stored as it is higher than 127. You can however do an explicit conversion; your value does consist of 8 bits after all.
byte b = (byte) 0b1111_1111
works because it simply disregards the 24 bits from the left hand side of the value. Now if you print it you will get -1 as value though as 0b1111_1111 represents 1 in 8 bit two complement form.
If you need it to represent the integer value 255 then you need to perform the following little trick:
int i = b & 0xFF;
which will actually do the following:
First it will convert b to the value 0xFFFFFFFF as integer using sign extension as all calculations default to integer, and it still thinks that b represents -1 after all.
Then it performs a bitwise AND with the value 0x000000FF (which is called a "mask"), resulting of course in the same value 0x000000FF which represents 255.
If you think this is a nuisance then you are right. Java should have used unsigned bytes, but it decided to use only one particular integer type that is signed. Maybe a bit overzealous but still a big improvement over e.g. C where you have way too many integer formats, and each of them may be represented differently on various machines.

How is short 128 = byte -128 while explicit casting in java ?

import java.util.Scanner;
public class ShortToByte{
public static void main (String args[]){
int i=0;
while (i<6){
Scanner sinput = new Scanner (System.in);
short a = sinput.nextShort();
byte b = (byte) a;
System.out.println("Short value : " + a + ",Byte value : " + b);
i++;
}
}
}
I am trying to understand conversion between different data types, but I am confused as how is short value of 128 = -128 in byte and also how is 1000 in short = -24 in byte ?
I have been using the following logic to convert short to byte :
1000 in decimal -> binary = 0000 0011 1110 1000
while converting to byte : xxxx xxxx 1110 1000 which is equivalent to : 232
I do notice that the correct answer is the two's complement of the binary value, but then when do we use two's complement to convert and when not as while converting 3450 from short to byte I did not use two's complement yet achieved the desired result.
Thank you!
Your cast from short to byte is a narrowing primitive conversion. The JLS, Section 5.1.3, states:
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.
(bold emphasis mine)
Numeric types are signed in Java. The short 128, represented in bits as
00000000 10000000
is narrowed to 8 bits as follows:
10000000
... which is -128. Now the 1 bit is no longer interpreted as +128; now it's -128 because of how two's complement works. If the first bit is set, then the value is negative.
Something similar is going on with 1000. The short 1000, represented in bits as
00000011 11101000
is narrowed to 8 bits as follows:
11101000
... which is -24.
From java datatypes:
byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)
Therefore 128 overflows to -128.

Converting Integer to Byte in Java [duplicate]

This question already has an answer here:
Promotion of byte to int or long
(1 answer)
Closed 7 years ago.
I have the following code:
int i =128;
byte b = (byte) i;
System.out.println( Integer.toBinaryString(i)); //10000000
System.out.println( Integer.toBinaryString(b)); //11111111111111111111111110000000
could someone explain why 1's were added to the left when casting from Integer to Byte and how could a byte carry more than 8 bits !?
You are calling .toBinaryString on the Integer class, so your number is treated as an Integer in any case.
The reason the second call has so many 1 is because it is a negative number. In Java, bytes are signed, so the maximum positive value is 127. By casting 128 into a byte you are actually representing -128. When you cast that small negative number into an 32 bit signed integer as you were doing, all those 1s appear at the beginning.

How to manually calculate the value of a typecasted byte value that exceeds the primary data type? [duplicate]

This question already has answers here:
java byte data type
(3 answers)
Closed 8 years ago.
since english isn't my main language and i've didn't find any pointers as to how to manually calculate the new number.
Example:
byte b = (byte) 720;
System.out.println(b); // -48
I know that most primary data types use the two complement.
Byte value ranges from -128 to 127, so it's expected to round the number down to something that fits in byte.
The Question is how do i manually calculate the -48 of the typecasted 720? I've read that i have to convert it to two complement, so taking the binary number, searching from right to left for the first one and then inverting all others and since byte only has 8 bits, take the first 8 bits. But that didn't quite work for me, it would be helpful if you would tell me how to calculate a typecasted number that doesn't fit into byte. Thanks for reading! :)
The binary representation of 702 is
10 1101 0000
Get rid of everything except the last 8 bits (because that's what fits into a byte).
1101 0000
Because of the leading 1, get the complement
0010 1111
and add 1
0011 0000
and negate the value. Gives -48.
In Java, integral types are always 2's complement. Section 4.2 of the JLS states:
The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers
You can mask out the least significant 8 bits.
int value = 720;
value &= 0xFF;
But that leaves a number in the range 0-255. Numbers higher than 127 represent negative numbers for bytes.
if (value > Byte.MAX_VALUE)
value -= 1 << 8;
This manually yields the -48 that the (byte) cast yields.
First what happens is the value (in binary) is truncated.
720 binary is 0b1011010000
We can only fit 8 bits 0b11010000
first digit 1, so the value is negative.
2's compliment gives you -48.
This is close to redundant with the answer posted by rgettman, but since you inquired about the two's complement, here is "manually" taking the 2's complement, rather than simply subtracting 256 as in that answer.
To mask the integer down to the bits that will be considered for a byte, combine it bitwise with 11111111.
int i = 720;
int x = i & 0xFF;
Then to take the two's complement:
if (x >> 7 == 1) {
x = -1 * ((x ^ 0xFF) + 1);
}
System.out.println(x);

signed byte type and bitwise operators in Java?

quoting from oracle website "byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)".
here, the first two lines are valid but the last is not
byte b = -128;
byte b1 = 127;
byte b2 = b>>>b1;//illegal
Q1) what is meant exactly by 8-bit signed? 128 in binary format would be 1000 0000 and -128 would need an extra bit for the negative sign, where it would fit if all the 8 bits are occupied.
Q2) for int, there is a unsigned right shift operator, but that seems illegal with bytes, why is it so. can overflow not be prevented in case of bytes. In case of int, it works
Thanks for your help
Just what it sounds like: There are 8 bits, holding 2^8 = 256 possible values. It's signed, so the range is frmo -128 through 127 (256 values). The most significant bit has a value of -128.
In Java, binary numeric promotion occurs with operations such as b >>> b1. Both types are promoted to int, and the result is an int. However, you can explicitly cast the result back to byte.
Here's the cast:
byte b2 = (byte) (b >>> b1);
The JLS, Section 5.6.2, talks about binary numeric promotion:
Widening primitive conversion (ยง5.1.2) is applied to convert either or
both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted
to float.
Otherwise, if either operand is of type long, the other is converted
to long.
Otherwise, both operands are converted to type int.
(emphasis mine)

Categories

Resources