Java uses 32 bits for the char tipe - so the max value is 65536.
But the following code give me the result reported in the title.
public static void main(String[] args) {
int a = 10000000;
char b = 33;
b = (char)a;
System.out.println((int)b);
}
A char is 16bit, not 32bit.
65535 is the maximum value of a char, and 10000000 is greater than that, so you cannot store that value in a char.
10000000 in binary is 100110001001011010000000
Now when casting that to char all the bits left of the 16 bits that "fit" are dropped, leaving you with 1001011010000000.
And binary 1001011010000000 in decimal is 38528.
Java uses 32 bits for the char tipe
no, Java uses 16 bit chars.
so the max value is 65536.
Almost - in terms of what is the char's max value, it's 65535, however, the max value of 2s-complement 32 bit value is 231, which is 2147483647.
But the following code give me the result reported in the title.
int a = 10000000;
char b = 33;
b = (char)a;
Well, 10000000 is sure greater than 65535, isn't it? What did you expect when trying to fit that number into a char? What you got is an overflow.
Related
Hi i hav a little problem about some code that i can't give an explanation about the result i have.
//what happens?
public static void what() {
int number = 2147483647;
System.out.println(number + 33);
}
//Here is my solution for the probleme
public static void what() {
long number = 2147483647;
System.out.println(number + 33);
}
The first code with the int number as variable gives me -2147483616 as result. So when i change the int to long i get the good result expected. So question is who can help me give and explanation of why int number + 33 = -2147483616
Java integers are based on 32 Bits. The first bit is kept for the sign (+ = 0 / - = 1).
So 2147483647 equals 01111111 11111111 11111111 11111111.
Adding more will force the value to turn to negative because the first bit is turned into a 1.
10000000 00000000 00000000 00000000 equals -2147483648.
The remaining 32 you are adding to -2147483648 brings you to your result of -2147483616.
The primitive int type has a maximum value of 2147483647, which is what you are setting number to. When anything is added to this value the int type cannot represent it correctly and 'wraps' around, becoming a negative number.
The maximum value of the long type is 9223372036854775807 so the second code snippet works fine because long can hold that value with no problem.
You have reached the maximum of the primitive type int (2147483647).
If int overflows, it goes back to the minimum value (-2147483648) and continues from there.
Consider the calculation of the second snippet, and what the result actually means.
long number = 2147483647;
number += 33;
The result in decimal is 2147483680, in hexadecimal (which more easily shows what the value means) it is 0x80000020.
For the first snippet, the result in hexacimal is also 0x80000020, because the result of arithmetic with the int type is the low 32 bits of the "full" result. What's different is the interpretation: as an int, 0x80000020 has the top bit set, and the top bit has a "weight" of -231, so this result is interpreted as -231 + 32 (a negative number). As a long, the 32nd bit is just a normal bit with a weight of 231 and the result is interpreted as 231 + 32.
The primitive type int is a 32-bit integer that can only store from -2^31 to 2^31 - 1 whereas long is a 64-bit integer so it can obviously store a much larger value.
When we calculate the capacity of int, it goes from -2147483648 to 2147483647.
Now you are wondering.. why is it that when the number exceeds the limit and I add 33 to it, it will become -2147483616?
This is because the data sort of "reset" after exceeding its limit.
Thus, 2147483647 + 1 will lead to -2147483648. From here, you can see that -2147483648 + 32 will lead to the value in your example which is -2147483616.
Some extra info below:
Unless you really need to use a number that is greater than the capacity of int, always use int as it takes up less memory space.
Also, should your number be bigger than long, consider using BigInteger.
Hope this helps!
Please explain how below code is working, as we know byte data type in java allows a range from -128 to 127.
My code snippet is:
public class DataTypes {
public static void main(String args[]){
byte b = (byte)140;
System.out.println(b);
}
}
Output: -116
A Byte will have 8 bits in its memory space. Using this space it can hold 256 values. This will span from -128 to 127 including 0. To support this spanning, a Byte value will be represented in binary format using two's compliment method. The MSB (Most Significant Bit) will determine the sign (0 - positive & 1 - negative) of the value.
If we consider the case of 140, it will be clear if we represent 140 in binary format which is 1000 1100. Remember the MSB will determine the sign and a 1 means the number is a negative value and 0 means it's a positive value. In this case we have a 1 making it a negative number.
If we apply reverse process to this two's compliment, we will first get 0111 0011 by inverting all the 1s to 0s and 0s to 1s. Then by adding 1, we get 0111 0100 which is equal to 116 in decimal format. But the MSB said it's a negative value, hence -116
Maybe this will help explain. The uppermost bit determines the 'sign'(positive or negative) of a variable. Since Java does not have an explicit 'unsigned' integer form the best you can do is apply a 'bitwise' operation to the item in advance of displaying it force it to be considered 'unsigned'...or you can display it using it's hex format which is inherently unsigned.
public class DataTypes {
public static void main(String args[]){
byte b = (byte)140;
System.out.println("hex value = "+String.format("0x%02X",b)+"\n");
System.out.println("dec value = "+String.format("%d",(b & 0xff))+"\n");
}
}
and a result of
hex value = 0x8C
dec value = 140
140 is a int. It is converted to a byte, according to the Java Language Specification, section 5.1.3, as follows:
A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits
The lowest 8 bits of the int with value 140 are 10001100, which is the correct value for the byte, but which is negative since its highest bit, the sign bit, is 1.
I think, when you cast the integer (140) to byte, the integer value converted into unsigned byte then b variable value is converted into signed byte. The number 140 considered as unsigned value because the number has not sign value indicator (+ or -)
Note about unsigned byte (the right value is representation (in file byte(s)) of left value):
0-127 = 0-127
(-128) - (-1) = 128 - 255
So, i'm fairly new to java, and i'm a bit confused about the byte system. So I made this program that converts integers to their base two value.
class Bits
{
public static void main(String[] args)
{
byte a;
a = 5;
System.out.println(Integer.toBinaryString(a)); /* prints 101 */
a = -1;
System.out.println(Integer.toBinaryString(a)); /* prints
11111111111111111111111111111111*/
}
}
It works as expected with positive numbers, but when I enter negative numbers, it gets weird. Now I know what two's compliment is, and it doesn't say that -1 is 11111111111111111111111111111111. It is supposed to be 11111111, right? When I change a to an int 255, which would be -1 as a byte, I get the normal result, 11111111, when I switch it to binary. Can someone explain to me why this is happening, or did I do something wrong. (I am using java 8 and i'm on a mac)
Integer.toBinaryString accepts an int as an argument. So a is casted from byte to int before being passed to the method. And yes the two's complement of -1 of a 32 bits integer is 11111111111111111111111111111111.
You should try with Integer.toBinaryString(a & 0xFF). So that a is widened to 32 bits, but then 24 most relevant bits are discarded through masking. The bit sign is kept since you were starting from a byte so the result will be correct.
You can verify it by converting the truncating the int converted from a and the parse it as an int and converting it back to a byte:
int counter = 0;
for (byte a = -128; counter <= 256; ++a, ++counter)
{
byte b = (byte)(Integer.valueOf(Integer.toBinaryString(a & 0xFF), 2) & 0xFF);
System.out.println(a+" == "+b);
}
Can someone please explain to me why I'm getting these results?
public static int ipv4ToInt(String address) {
int result = 0;
// iterate over each octet
for(String part : address.split(Pattern.quote("."))) {
// shift the previously parsed bits over by 1 byte
result = result << 8;
System.out.printf("shift = %d\n", result);
// set the low order bits to the current octet
result |= Integer.parseInt(part);
System.out.printf("result = %d\n", result);
}
return result;
}
For ipv4ToInt("10.35.41.134"), I get:
shift = 0
result = 10
shift = 2560
result = 2595
shift = 664320
result = 664361
shift = 170076416
result = 170076550
10.35.41.134 = 170076550
This is the same result that I get when I do the math myself.
For ipv4ToInt("192.168.0.1"), I get:
shift = 0
result = 192
shift = 49152
result = 49320
shift = 12625920
result = 12625920
shift = -1062731776
result = -1062731775
192.168.0.1 = -1062731775
For this one, when I do the math manually, I get 3232235521.
Interestingly:
3232235521 = 11000000101010000000000000000001
And when I enter 1062731775 into my Windows calc and hit the +/- button, I get:
-1062731775 = 11111111111111111111111111111111 11000000101010000000000000000001
The function still works for my purposes, but I'm just really curious to know why on earth result is going negative when I do that last bit shift?
Because of bit overflow in your case!
In Java, the integer is also 32 bits and range is from -2,147,483,648 to 2,147,483,647.
12625920 << 8 crosses the limit of 2^31-1 and hence,the result turns negative...
The result just overturns from -ve side and hence,whatever range is left from the positive side is accompanied by that much from negative side!!!
As suggested by everyone,you should use long variable to avoid overflow!
All primitives in java are signed - They can be positive or negative. The highest bit is used to control this, so when it gets set, the number becomes negative.
Try using a long instead - that will give you the wanted result, as longs can be much larger without overflow being hit.
11000000101010000000000000000001 is 32 bits. The value it represents depends on how you interpret those bits:
as a 32bit signed integer, it is negative (because the left-most bit is 1)
as a 32bit unsigned integer, it is positive (like every other unsigned integer)
as the lowers bits of a long (signed or unsigned), it would give a positive value (if the left-most bits stay 0)
Java uses signed integers, so if you print the value, you'll see a negative number. That does not mean your bits are wrong.
It matters only for printing, you can use these ways for printing a positive integer:
1) change result to long (java will do the work for you).
2) handle signed int as unsigned int by yourself (possibly make a method int2string(int n) or toString(int n).
3) Integer.toUnsignedString(int) is you are using java 8.
As far as I understand, your are parsing an IP address, remember, java use signed data types, you can't have a 32 bits integer.
change result to long to fix that.
I write the following sample code:
public static void main(String[] args) throws Exception
{
byte number_1 = 127;
byte number_2 = (byte) 128;
System.out.println("number_1 = " + number_1);
System.out.println("number_2 = " + number_2);
}
I get the following result in output:
number_1 = 127
number_2 = -128
I know range of a byte data type( -128 to 127).
Is my sample is correct? What happened? Is there a two's complement operation? I don't understand this behavior.
Because one byte can hold upto -128 to 127 only, This is expected behavior of overflow
Check with this loop
for(int index = 0 ; index < 258 ; index ++ ){
System.out.println((byte)index);
}
Also See
Endless for loop
Nice comic illustration
This is because of byte range . A byte can store values from -128 to 127 only.
You're seeing the effect of a narrowing primitive conversion: casting the integer literal 128 to a byte results all all but the last byte being thrown out. The last byte of an integer has value 10000000, which when interpreted in two's complement as a one-byte value comes out to -128.
In contrast, the same value interpreted as a four-byte value filled with zeroes on the left, i.e. 00000000 00000000 00000000 10000000, equals 128.
From the official documentation on primitive 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).
To respond your question : How to Set greater than 127 int byte variable in java ?
The best way to represent an unsigned byte is to use a signed integer, because the Java VM represents bytes as 32 bits, you're not saving anything by using a byte.
Because one byte can hold upto -128 to 127 only, when you transform a int which is
more than 127 or less than -127, the java compiler makes the change automatically.
In fact, the following statement
byte number_2 = (byte) 128;
has been changed to
byte number_2 = (byte) -128;
Once you check out the bytecode using javap, you will find it.