Java - explicit conversion to char/short - java

can anyone tell me why this explicit conversion gives different results, even if size of short/char is both 16bits?
package jh;
public class Main {
public static void main(String[] args) {
byte b = (byte)255;
System.out.println("Size of short: " + Short.SIZE);
System.out.println("Size of char: " + Character.SIZE);
System.out.println((int)((short)b));
System.out.println((int)((char)b));
}
}
Output:
Size of short: 16
Size of char: 16
-1
65535

From Java datatypes doc
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). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
So in short (pardon the pun), bitwise they are the same. But char represents a different numeric value for the same bit pattern as short.
This is also accompanied by the sign extension feature: (byte) 255 is going to mean a byte value, with all bits set (0b11111111), which is -1, in twos complement. When converting upwards, Java does a sign extension operation, so if the sign bit is 0, all the higher bits will be 0 too, but when the sign bit is 1, all higher bits will be 1 too. This now means that -1 will mean -1 in all signed, integer datatypes (0b1111111111111111 for short in this example). But not char - which when has all bits set, equals the positive maximum value - 65535.

byte is signed and only holds values -128..127. When you assign 255 it wraps around and becomes -1.
(short)b is -1.
char however is the only unsigned type in Java, it has values 0..65535, so (char)-1 wraps around again and becomes 65535.

byte b = (byte)255; this assigns the value -1 to b since byte is signed. When you cast -1 to short you get -1. When you cast -1 to char you get 65535 since the range of char lies between 0 and 65535

Related

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.

Store signed value in Byte

I was trying to store byte value in a variable and trying to perform some logic based upon this calculation.
byte mByteValue = -129; // Holding byte value
Problem is I am always getting value 127, due to which my logic fails everytime.
Any specific reason behind this, why its behaving strange in my case?
A byte in java is a signed 8-bit value. 8 bits gives you 256 possible values, but since a byte is signed and can represent positive and negative values, those 256 values must be roughly split in half across the possible positive and negative values. So you can't store negative values past -128; in particular don't expect to be able to store -256.
What you're actually observing when your byte has the value 127 is known as overflow (see this wiki article)
If you need to manipulate values outside this range, as in your example code, or e.g. an unsigned byte, at some point you'll need to make use of a wider integer type, like short.
The standard libraries provide these limits as Byte.MIN_VALUE and Byte.MAX_VALUE (docs here and here).
The range of byte is from -128 to 127. You can not store any value beyond these range.
This is because byte is 8 bits. So the maximum positive number stored at byte is -
2^7 -1 = 127. // since the first bit is sing bit; 0 for positive
And minimum negative number stored at byte is-
2^7 = -128 //since the first bit is sign bit; 1 for negative.
And if you use unsigned byte the it would be 255.
To correctly convert a byte to an int use mByteValue & 0xFF. You can read more about the Two's complement here: https://en.wikipedia.org/wiki/Two%27s_complement.

What does it mean when we say the width of Byte in java is 8 bit?

I can store numbers ranging from -127 to 127 but other than that it is impossible and the compiler give warning. The binary value of 127 is 01111111, and 130 is 10000010 still the same size (8 bits) and what I think is I can store 130 in Byte but it is not possible. How did that happen?
Java does not have unsigned types, each numeric type in Java is signed (except char but it is not meant for representing numbers but unicode characters).
Let's take a look at byte. It is one byte which is 8 bits. If it would be unsigned, yes, its range would be 0..255.
But if it is signed, it takes 1 bit of information to store the sign (2 possible values: + or -), which leaves us 7 bits to store the numeric (absolute) value. Range of 7 bit information is 0..127.
Note that the representation of signed integer numbers use the 2's complement number format in most languages, Java included.
Note: The range of Java's byte type is actually -128..127. The range -127..127 only contains 255 numbers (not 256 which is the number of all combinations of 8 bits).
In Java, a byte is a signed data type. You are thinking about unsigned bytes, in which case it is possible to store the value 130 in 8 bits. But with a signed data type, that also allows negative numbers, the first bit is necessary to indicate a negative number.
There are two ways to store negative numbers, (one's complement and two's complement) but the most popular one is two's complement. The benefit of it is that for two's complement, most arithmetic operations do not need to take the sign of the number into account; they can work regardless of the sign.
The first bit indicates the sign of the number: When the first bit is 1, then the number is negative. When the first bit is 0, then the number is positive. So you basically only have 7 bits available to store the magnitude of the number. (Using a small trick, this magnitude is shifted by 1 for negative numbers - otherwise, there would be two different bit patterns for "zero", namely 00000000 and 10000000).
When you want to store a number like 130, whose binary representation is 10000010, then it will be interpreted as a negative number, due to the first bit being 1.
Also see http://en.wikipedia.org/wiki/Two%27s_complement , where the trick of how the magnitude is shifted is explained in more detail.

C datatypes in Java

I have an application in C and need to re-write it to Java. I have a problem with data types. I am not sure which data type is equal to the C ones in Java.
There are those I need to find out equal datatypes in java programming language for.
unsigned char
unsigned short
short int
unsigned long
I'd pick something based on the ranges you need
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). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -2^31 and a maximum value of 2^31 - 1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 2^32 - 1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -2^63 and a maximum value of 2^63 - 1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2^64 - 1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.
short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
ref: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Java doesn't have unsigned types (apart from char, which pretends not to be a number)
byte is one byte, in range -128 to 127
char is two bytes (unsigned), but only generally used for characters, not numbers
short is also two bytes, in range -32768 to 32767
int is four bytes
long is eight bytes
Edit -- char is unsigned (thanks to Hot Licks in comments)

How to calculate the range of primitive data types?

According to docs.oracle.com:-
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). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
Byte - 8 bits
2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0
128 64 32 16 8 4 2 1)
Adding all these numbers we get a total of 255. Then how's the range which is -128 to 127 calculated. Is it hard-coded somewhere or there's some more technicality to this range?
Any suggestions would be appreciated.
Let's calculate range for 1 Byte
1 bit can take 0 or 1
1 Byte = 8 Bits
The first bit is used as a sign ( - or + )
then remaining bits are 7
so we can write 2^7 = 128 different numbers for one sign
we get 0 as a positive sign. then we have 128 numbers for the negative side,127 numbers for the positive side and 0 (zero)
so the range is -128 to 127 including 0
It is a signed type, meaning, it still has a range of 255 (as you have correctly calculated), but it starts at -128. So half the range is below zero, 1 possible number is = (zero) and the remaining 127 are above 0.
The first bit is the sign. (1 - minus, 0 - plus)
Formula for Range calculation is : -2^(n-1) to (2^(n-1)-1)
where n = no. of bits of primitive datatype.
Example:
For int datatype, n is 32, in short datatype, n is 16 etc.
So, int range will be: -2^(32-1) to (2^(32-1)-1)
By using the same formula Range of byte, short, float and double could be calculated.
That's because the first bit is used for the sign, since the data type is signed.
Please refer to http://en.wikipedia.org/wiki/Signed_number_representations
Since there is no unsigned primitive types in Java (like C or C#), is usual to cast it to a bigger type if you need to "overflow" the boundaries.
The last bit i.e. number 8 we are writing it 2^7 is a sign bit that decides negative or positive sign so it is 2^0 +2^1 +2^2 +2^3 +2^4 +2^5+ 2^6
Formula to calculate range in Java
-2(n-1) to +2(n-1)-1
Where n is the number of bit (1 byte= 8 bit)
So, for byte type range would be:
-2(8-1) to +2(8-1)-1
or, -2(7) to +2(7)-1
or, -128 to +127
it results from the standard representation of signed values as binary numbers. For a full description see http://en.wikipedia.org/wiki/Two%27s_complement.
-Rich
Let's calculate range for 1 Byte in C Langauge Datatype char
In case of char dataype lets consider -
1 Byte = 8 Bits
2^8 = 256
so we can write 2^8 = 256
In case of unsigned 0 to positive integers only.
4.1 In case of signed
we have 128 numbers for the negative side, 0 (zero) and 127 numbers for the positive side
so the range is -128 0 +127
Here 0 is taking one bit
Bit consists of 0’s and 1’s.byte normally consists of 8 bits.so the values can be calculated using the general formula which is given below,
no of values data type can have=2^n(2 power n), where n represents no of bits.
so the value of byte data type=2^8(i.e 1 byte=8 bits),here n=8
byte value=256
And it should be shared equal on both sides of zero ( half values at negative and half value at positive ). Hence the range for byte is from -128 to 127.
Range of data types
so now we came to know that how we are calculating the Range of the integer data types.This logic is applicable for all the integer data types.
The full details of all the data types are given below,
S.NO Data Type Bits Ranges values
1 boolean 1 – true or false(1 or 0)
2 byte 8 -128 to 127. 256(2^8)
3 short 16 -32,768 to 32,767 65,536(2^16)
4 int 32 -2^31 to (2^31)-1 2^32
5 long 64 Refer NOTE 2^64
6 float 32 Refer NOTE ———
7 double 64 Refer NOTE ———-
8 char 16 0 to 65,535 65,536(2^16)

Categories

Resources