Java: right shift on negative number - java

I am very confused on right shift operation on negative number, here is the code.
int n = -15;
System.out.println(Integer.toBinaryString(n));
int mask = n >> 31;
System.out.println(Integer.toBinaryString(mask));
And the result is:
11111111111111111111111111110001
11111111111111111111111111111111
Why right shifting a negative number by 31 not 1 (the sign bit)?

Because in Java there are no unsigned datatypes, there are two types of right shifts: arithmetic shift >> and logical shift >>>. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
Arithmetic shift >> will keep the sign bit.
Unsigned shift >>> will not keep the sign bit (thus filling 0s).
(images from Wikipedia)
By the way, both arithmetic left shift and logical left shift have the same result, so there is only one left shift <<.

Operator >> called Signed right shift, shift all the bits to right a specified number of times. Important is >> fills leftmost sign bit (Most Significant Bit MSB) to leftmost bit the after shift. This is called sign extension and serves to preserve the sign of negative numbers when you shift them right.
Below is my diagrammatic representation with an example to show how this works (for one byte):
Example:
i = -5 >> 3; shift bits right three time
Five in two's complement form is 1111 1011
Memory Representation:
MSB
+----+----+----+---+---+---+---+---+
| 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 |
+----+----+----+---+---+---+---+---+
7 6 5 4 3 2 1 0
^ This seventh, the left most bit is SIGN bit
And below is, how >> works? When you do -5 >> 3
this 3 bits are shifted
out and loss
MSB (___________)
+----+----+----+---+---+---+---+---+
| 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 |
+----+----+----+---+---+---+---+---+
| \ \
| ------------| ----------|
| | |
▼ ▼ ▼
+----+----+----+---+---+---+---+---+
| 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
+----+----+----+---+---+---+---+---+
(______________)
The sign is
propagated
Notice: the left most three bits are one because on each shift sign bit is preserved and each bit is right too. I have written The sign is propagated because all this three bits are because of sign(but not data).
Also because of three right shift right most three bits are losses out.
The bits between right two arrows are exposed from previous bits in -5.
I think it would be good if I write an example for a positive number too. Next example is 5 >> 3 and five is one byte is 0000 0101
this 3 bits are shifted
out and loss
MSB (___________)
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 |
+----+----+----+---+---+---+---+---+
| \ \
| ------------| ----------|
| | |
▼ ▼ ▼
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+----+----+----+---+---+---+---+---+
(______________)
The sign is
propagated
See again I writes The sign is propagated, So leftmost three zeros are due to sign bit.
So this is what operator >> Signed right shift do, preserves the sign of left operand.
[your answer]
In your code, you shifts -15 to right for 31 times using >> operator so your right most 31 bits are loosed and results is all bits 1 that is actually -1 in magnitude.
Do you notice that In this way -1 >> n is equivalent to not a statement.
I believe if one do i = -1 >> n it should be optimized to i = -1 by Java compilers, but that is different matter
Next, It would be interesting to know in Java one more right shift operator is available >>> called Unsigned Right Shift. And it works logically and fills zero from left for each shift operation. So at each right shift you always get a Zero bit on left most position if you use unsigned right shift >>> operator for both Negative and Positive numbers.
Example:
i = -5 >>> 3; Unsigned shift bits right three time
And below is my diagram that demonstrates how expression -5 >>> 3 works?
this 3 bits are shifted
out and loss
MSB (___________)
+----+----+----+---+---+---+---+---+
| 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 |
+----+----+----+---+---+---+---+---+
| \ \
| ------------| ----------|
| | |
▼ ▼ ▼
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 |
+----+----+----+---+---+---+---+---+
(______________)
These zeros
are inserted
And you can notice: this time I am not writing that sign bits propagated but actually >>> operator insert zeros. Hence >>> doesn't preserves sign instead do logical right shift.
In my knowledge unsigned right shift is useful in VDU (Graphics programming),Although I haven't used it but read it some where in past.
I would suggest you read this: Difference between >>> and >> : >> is arithmetic shift right, >>> is logical shift right.
Edit:
Some interesting about Unsigned Right Shift Operator >>> operator.
The unsigned right shift operator >>> produces a pure value that is its left operand right-shifted with zero 0 extension by the number of bits specified by its right operand.
Like >> and <<, operator >>> also operator never throws an exception.
The type of each operand of the unsigned right shift operator must be an integer data type, or a compile-time error occurs.
The >>> operator may perform type conversions on its operands; unlike arithmetic binary operators, each operand is converted independently. If the type of an operand is byte, short, or char, that operand is converted to an int before the value of the operator is computed.
The type of the value produced by the unsigned right shift operator is the type of its left operand. LEFT_OPERAND >>> RHIGT_OPERAND
If the converted type of the left operand is int, only the five least significant bits of the value of the right operand are used as the shift distance. (that is 25 = 32 bits = number of bit in int)
So, the shift distance is in the range 0 through 31.
Here, the value produced by r >>> s is the same as:
s==0 ? r : (r >> s) & ~(-1<<(32-s))
If the type of the left operand is long, then only the six least significant bits of the value of the right operand are used as the shift distance.(that is 25 = 64 bits = number of bit in long)
Here, the value produced by r >>> s is the same as the following:
s==0 ? r : (r >> s) & ~(-1<<(64-s))
A Interesting Reference: [Chapter 4] 4.7 Shift Operators

Because >> is defined as an arithmetic right shift, which preserves the sign. To get the effect you expect, use a logical right shift, the >>> operator.

Related

How do I represent potency in Java with all zeros? [duplicate]

What function does the ^ (caret) operator serve in Java?
When I try this:
int a = 5^n;
...it gives me:
for n = 5, returns 0
for n = 4, returns 1
for n = 6, returns 3
...so I guess it doesn't perform exponentiation. But what is it then?
The ^ operator in Java
^ in Java is the exclusive-or ("xor") operator.
Let's take 5^6 as example:
(decimal) (binary)
5 = 101
6 = 110
------------------ xor
3 = 011
This the truth table for bitwise (JLS 15.22.1) and logical (JLS 15.22.2) xor:
^ | 0 1 ^ | F T
--+----- --+-----
0 | 0 1 F | F T
1 | 1 0 T | T F
More simply, you can also think of xor as "this or that, but not both!".
See also
Wikipedia: exclusive-or
Exponentiation in Java
As for integer exponentiation, unfortunately Java does not have such an operator. You can use double Math.pow(double, double) (casting the result to int if necessary).
You can also use the traditional bit-shifting trick to compute some powers of two. That is, (1L << k) is two to the k-th power for k=0..63.
See also
Wikipedia: Arithmetic shift
Merge note: this answer was merged from another question where the intention was to use exponentiation to convert a string "8675309" to int without using Integer.parseInt as a programming exercise (^ denotes exponentiation from now on). The OP's intention was to compute 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0 = 8675309; the next part of this answer addresses that exponentiation is not necessary for this task.
Horner's scheme
Addressing your specific need, you actually don't need to compute various powers of 10. You can use what is called the Horner's scheme, which is not only simple but also efficient.
Since you're doing this as a personal exercise, I won't give the Java code, but here's the main idea:
8675309 = 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0
= (((((8*10 + 6)*10 + 7)*10 + 5)*10 + 3)*10 + 0)*10 + 9
It may look complicated at first, but it really isn't. You basically read the digits left to right, and you multiply your result so far by 10 before adding the next digit.
In table form:
step result digit result*10+digit
1 init=0 8 8
2 8 6 86
3 86 7 867
4 867 5 8675
5 8675 3 86753
6 86753 0 867530
7 867530 9 8675309=final
As many people have already pointed out, it's the XOR operator. Many people have also already pointed out that if you want exponentiation then you need to use Math.pow.
But I think it's also useful to note that ^ is just one of a family of operators that are collectively known as bitwise operators:
Operator Name Example Result Description
a & b and 3 & 5 1 1 if both bits are 1.
a | b or 3 | 5 7 1 if either bit is 1.
a ^ b xor 3 ^ 5 6 1 if both bits are different.
~a not ~3 -4 Inverts the bits.
n << p left shift 3 << 2 12 Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
n >> p right shift 5 >> 2 1 Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
n >>> p right shift -4 >>> 28 15 Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.
From here.
These operators can come in handy when you need to read and write to integers where the individual bits should be interpreted as flags, or when a specific range of bits in an integer have a special meaning and you want to extract only those. You can do a lot of every day programming without ever needing to use these operators, but if you ever have to work with data at the bit level, a good knowledge of these operators is invaluable.
It's bitwise XOR, Java does not have an exponentiation operator, you would have to use Math.pow() instead.
XOR operator rule =>
0 ^ 0 = 0
1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1
Binary representation of 4, 5 and 6 :
4 = 1 0 0
5 = 1 0 1
6 = 1 1 0
now, perform XOR operation on 5 and 4:
5 ^ 4 => 1 0 1 (5)
1 0 0 (4)
----------
0 0 1 => 1
Similarly,
5 ^ 5 => 1 0 1 (5)
1 0 1 (5)
------------
0 0 0 => (0)
5 ^ 6 => 1 0 1 (5)
1 1 0 (6)
-----------
0 1 1 => 3
It is the XOR bitwise operator.
Lot many people have already explained about what it is and how it can be used but apart from the obvious you can use this operator to do a lot of programming tricks like
XORing of all the elements in a boolean array would tell you if the array has odd number of true elements
If you have an array with all numbers repeating even number of times except one which repeats odd number of times you can find that by XORing all elements.
Swapping values without using temporary variable
Finding missing number in the range 1 to n
Basic validation of data sent over the network.
Lot many such tricks can be done using bit wise operators, interesting topic to explore.
XOR operator rule
0 ^ 0 = 0
1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
a^b ==> 0011 1100 (a)
0000 1101 (b)
------------- XOR
0011 0001 => 49
(a ^ b) will give 49 which is 0011 0001
As others have said, it's bitwise XOR. If you want to raise a number to a given power, use Math.pow(a , b), where a is a number and b is the power.
AraK's link points to the definition of exclusive-or, which explains how this function works for two boolean values.
The missing piece of information is how this applies to two integers (or integer-type values). Bitwise exclusive-or is applied to pairs of corresponding binary digits in two numbers, and the results are re-assembled into an integer result.
To use your example:
The binary representation of 5 is 0101.
The binary representation of 4 is 0100.
A simple way to define bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.
With 4 and 5, the only difference is in the last place; so
0101 ^ 0100 = 0001 (5 ^ 4 = 1) .
It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.
ex :-
To use your example:
The binary representation of 5 is 0101.
The binary representation of 4 is 0100.
A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.
0101 ^ 0100 = 0001 (5 ^ 4 = 1) .
To perform exponentiation, you can use Math.pow instead:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Math.html#pow%28double,%20double%29
As already stated by the other answer(s), it's the "exclusive or" (XOR) operator. For more information on bit-operators in Java, see: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html
That is because you are using the xor operator.
In java, or just about any other language, ^ is bitwise xor,
so of course,
10 ^ 1 = 11.
more info about bitwise operators
It's interesting how Java and C# don't have a power operator.
It is the bitwise xor operator in java which results 1 for different value (ie 1 ^ 0 = 1) and 0 for same value (ie 0 ^ 0 = 0).
^ is binary (as in base-2) xor, not exponentiation (which is not available as a Java operator). For exponentiation, see java.lang.Math.pow().
It is XOR operator. It is use to do bit operations on numbers. It has the behavior such that when you do a xor operation on same bits say 0 XOR 0 / 1 XOR 1 the result is 0. But if any of the bits is different then result is 1.
So when you did 5^3 then you can look at these numbers 5, 6 in their binary forms and thus the expression becomes (101) XOR (110) which gives the result (011) whose decimal representation is 3.
As an addition to the other answers, it's worth mentioning that the caret operator can also be used with boolean operands, and it returns true (if and only if) the operands are different:
System.out.println(true ^ true); // false
System.out.println(true ^ false); // true
System.out.println(false ^ false); // false
System.out.println(false ^ true); // true
^ = (bitwise XOR)
Description
Binary XOR Operator copies the bit if it is set in one operand but not both.
example
(A ^ B) will give 49 which is 0011 0001
In other languages like Python you can do 10**2=100, try it.

Convert 64bit data to signed long value

I have something like this:
byte[0] = 0001 0100 0011 0100 (dec value: 5172)
byte[1] = 0000 0000 0111 1100 (dec value: 124)
byte[2] = 0000 0000 0000 0000 (dec value: 0)
byte[3] = 0000 0000 0000 0000 (dec value: 0)
I would like to combine them and make one long value in Java. How to do that?
Can it be converted on this way?
result = 0 + (0 x 2^16) + (0 x 2^16) + (124 x 2^32) + (5127 x 2^48)
ie.
result = byte[3] + (byte[2] x 2^16) + (byte[1] x 2^32) + (byte[0] x 2^48)
Edit: Let me try to explain better. When I open tool ModScan32 and connect to my device I see some registers. In this tool there are different kind of options how to show data. One of them are to represent them as binary or decimal. When I choose binary or decimal I get values as they are in my example above. When I read this data with my software I get exactly the same (converted values) in the decimal. Now my question is if it is necessary to hold data in 4 16 bit registers and i know their decimal values what is the proper way to combine those values from registers and get real value?
Your idea is basically OK. There are a few things to be aware of.
I believe the result you are after in your case is 0001010000110100000000000111110000000000000000000000000000000000.
Here’s an attempt that does not work:
int[] registers = { 5172, 124, 0, 0 };
long result = registers[0] << 48 | registers[1] << 32 | registers[2] << 16 | registers[3];
System.out.println(Long.toBinaryString(result));
<< 48 means shift 48 bits to the left, that should be good enough, right? | is a bitwise logical or, it fills the 1 bits from either operand into the same bit posistion of the result. You could use + instead if you preferred.
This prints:
10100001101000000000001111100
We only have the first 32 bits of the result, that’s not good enough. When trying to read it, note that Long.toBinaryString() does not include leading zeroes. Just imagine 3 zeroes in front of the number.
But what went worng? Where did the last 32 bits go? Even when they were all zeroes. The problem is that we are doing the calculation in ints, they are 32 bits, not 64. EDIT: My previous explanation was not entirely correct on this point. The truth is: When doing << on an int, only the last 5 bits of the right operand are considered, so since 48 is 110000 in binary, only 10000 is used, so the shift is the same as << 16. Similarly << 32 is the same as << 0, no shift at all. So registers[0] and [1] have ended up in the wrong bit posistion. The solution is easy when you know it: we need to convert to long before doing the calculation. Now the last 6 bits of the right operand are used, so 48 and 32 are understood as 48 and 32:
long result = ((long) registers[0]) << 48 | ((long) registers[1]) << 32 | registers[2] << 16 | registers[3];
This time we get
1010000110100000000000111110000000000000000000000000000000000
Again, imagine 3 zero bits in front and all is as expected.
There is one more thing. Say you got a negative value from a register, for example:
int[] registers = { 5172, -124, 0, 0 };
The calculation that just worked now gives us
1111111111111111111111111000010000000000000000000000000000000000
This time there are 64 bits printed, so it’s easy to see there are too many 1s in the beginning. They come from the int representation of -124. The solution is to mask them out:
int[] registers = { 5172, -124, 0, 0 };
long result = ((long) registers[0] & 0xFFFF) << 48
| ((long) registers[1] & 0xFFFF) << 32
| (registers[2] & 0xFFFF) << 16
| (registers[3] & 0xFFFF);
System.out.println(Long.toBinaryString(result));
0xFFFF is 16 1 bits, and & is the bitwise logical ‘and’, giving a 1 bit in the result only in positions where both operands have a 1 bit. Now -124 gets masked to 1111111110000100 so the result is the expected:
1010000110100111111111000010000000000000000000000000000000000
That should do it.

Java Binary to Integer

I looked a couple of different way to convert binary to integer in JAVA.
But I couldn't figure out why this works?
int res = 0;
res += 1 << 1;
The res turns out to be 2, I know it shifts towards left 1 bit and became 10 in binary. But I'm confusing how it converts from binary to integer, i want to know the mechanism.
Thanks
First of all, let's clear up some terminology first. What you believe to be an integer is actually a number in the base 10 notation, which in case of Java is a natural number that is represented using the ten digits from 0 to 9 (hence base 10).
In binary notation we are dealing with just two digits instead to represent all natural numbers. Both binary (base 2) and decimal numbers (base 10) are integers.
Digit shifting is multiplication or division by the base of the number
The bit shifting effect you observed can be easily explained using base 10 numbers you are already familiar with. Imagine you have a strip of square fields pre-filled with 0s. In each field you can write a digit from 0 to 9, and lets assume these fields are called "bits". You write the number 7 into that strip aligned to the right hand side:
0|0|0|0|0|7
Imagine that whole strip represents the integer 7 now. What bit shifting effectively does, is moving those digits in that strip either to the left or the right, while filling up the previously occupied spots with 0s. Imagine, we are shifting our 7 to the left by one spot:
0|0|0|0|7|0
By shifting the number to the left we practically performed a quick multiplication by 10 (remember, that is the base of our numeral system we're dealing with here).
When you shift that number to the right by one spot, you perform a division by 10.
Bit shifting is multiplication or division by 2
The same applies to binary numbers, the dominant storage format for numbers in computers. Binary numbers are comprised of just two digits, 1s and 0s.
Just take a quick look at the following table for getting a better understanding of binary numbers:
+-------------------+
| Decimal | Binary |
+---------+---------+
| 0000001 | 0000001 |
| 0000002 | 0000010 |
| 0000003 | 0000011 |
| 0000004 | 0000100 |
| 0000005 | 0000101 |
| 0000006 | 0000110 |
| 0000007 | 0000111 |
| ... | ... |
+---------+---------+
We perform multiplications by 2 when we shift the number in our strip to the left, and we perform divisions by 2 when we shift the number to the right. Just check out the table, and look up the decimal number 1. Multiply it by 2 and look at the binary representation. Multiply that again by 2 (decimal 4) and look at the binary notation. The binary digit 1 just moves to the left one by one due to the multiplication by two.
res+= 1<<1; can be written as res = res + 1<<1;
if you take 1<<1 which means 1 is represented as 0x00000001 = 00000000 00000000 00000000 00000001
when you do a right shift it becomes 00000000 00000000 00000000 00000010
which is 0x00000002 which is 2 in decimal value

Which bit actually shift the << operator?

I confused with an operator which provides arithmetic shifts <<, >> in Java
For example I have this binary number:
0000 0101 // It is actually 5 in dec system
And now I want to shift this number to the left by 2 positions. I am doing this ( this is only concept of shifting bits) :
0000 0101 << 2
And now I do not know: if I need to shift high bit by 2 positions and fill with zero in right side OR I need to shift whole number (101) by 2 positions?
Second option :)
For instance, 0110001 << 2 = 1000100
The other operators are:
signed right shift (>>).
0011001 >> 2 = 0000110
1011001 >> 2 = 1110110
The leftmost bit is used as left padding. This is done to propagate the sign bit (highest bit).
unsigned right shift (>>>)
1110001 >> 2 = 0011100
Since the number is considered unsigned, there is nothing to propagate, just pad with zeros!

How does Java handle arguments separated by |?

How does Java handle arguments separated by | ?
for example
private void foo(int i) {
System.out.println(i);
}
private void bar() {
foo(1 | 2 | 1);
}
Which would give the output
3
I've seen this used in SWT/JFace widget constructors. What I can't figure out is how the value of i is decided.
The | is a bitwise or-operator.
foo(1 | 2 | 1);
means call foo with the argument 1 bitwise-or 2 bitwise-or 1.
1 in binary is 01
2 in binary is 10
Bitwise or of 01 and 10 is 11 which is 3 in decimal.
Note that the | operator can be used for booleans as well. Difference from the || operator being that the second operand is evaluated even if the first operand evaluates to true.
Actually, all bitwise operators work on booleans as well, including the xor ^. Here however, there are no corresponding logical operator. (It would be redundant, since there is no way of doing a "lazy" evaluation of ^ :)
it is using the bitwise OR operator. For starters, 1 | 1 = 1 so the second 1 is redundant. If we remove the redundant 1 we are left with the equation 1 | 2 = 3. Looking at it in 2 bit binary it looks like:
01 | 10 = 11
The or operator will match up the corresponding bits from each or the values and if there is one 1 in either or both values for a given position, the result is a 1. If both values for both the corresponding bits then the result is 0.

Categories

Resources