I do program with Java for about one year, but still found something I do not know.
How does:
new Font(FontFamily.TIMES_ROMAN, 12, 1 | 4);
How | does work with integers?
Thank You
P.S. I googled a lot.
The | operator calculates the "bit-wise OR" of its operands. To understand it you have to convert the operands to binary: it produces a "0" bit if the bit is not set in either numbers, and a "1" bit if it is set in either.
With your numbers, the result of 4|1 is 5 because:
4 = 100
1 = 001
4|1 = 101 = 5
The bit-wise OR operator is related to the "bit-wise AND" operator &, which produces a "0" if the bit is not set in one of the numbers and a "1" bit if it is set in both.
Since these operators work on the bit-wise representation of their arguments they can be hard to understand when you're used to working on decimal (base 10) numbers. The following relation holds, which makes it easy to derive the result of one when you have the other:
a + b = (a|b) + (a&b)
It is a bitwise OR operator , operates on one or more bit patterns or binary numerals at the level of their individual bits.
The bitwise ^ operator performs a bitwise exclusive OR operation.
OR bitwise operation will return 1 if any of operand is 1 and zero only if both operands are zeros.
You can get the complete description in the JLS 15.22.1.
0|0 = 0
0|1 = 1
1|0 = 1
1|1 = 1
Hence in your case , the operands are 1 and 4 . Converting them into binary (only the last 4 digits) will be 0100 and 0001 respectively. Apply the | now bit by bit :
0 1 0 0
0 0 0 1
---------
0 1 0 1 = (5 in base 10)
The | is called bitwise OR. This works by:
Converting each number to binary
Doing boolean OR (||) on each digit in a matching position (0 is false, 1 is true)
Converting the result back to decimal
For example,
100 | 4
OR 001 | 1
-------+--
101 | 5
The properties on the Font constructor are designed so in binary, exactly one digit is a 1. By ORing these numbers, you get the digits turned on that represent the options that are ORed.
Related
I trying to know to know how java finds the result is -ve or +ve for Bitwise operations?
int x=-5;
int y=8;
System.out.println(x&y); //8
System.out.println(x|y); //-5
x->1 0 1 1 (2's complement)
y->1 0 0 0
x & y -> 1 0 0 0 ->8
x | y -> 1 0 1 1 ->-5(2's complement)
How java knows 1 0 1 1 is -5 ?
why doesn't it directly give o/p as 1 0 1 1's decimal equivalent 11 ?
Does it apply 2's complement on every result ?
I have seen the Assembly Code . It is IAND and IOR instructions.
You are running the bitwise operators on 32-bit integers. So, the number "8" really has a lot of zeros in front, while "-5" has a lot of ones:
8 -> 0...01000
-5 -> 1...11011
So, Java does not need to "know" anything about the outcome or operands of the bitwiese operations. The "8" is a 32-bit number that starts with a 0, so it is positive. The "-5" is a 32-bit number that starts with a "1", so it is negative.
So, the answer to your question
Does it apply 2's complement on every result ?
is: Yes, since all integers are signed number in Java, using 2's complement.
What is "consecutive in gray code" supposed to mean? I mean 10 and 11 are consecutive in decimal system but what is "consecutive in gray code" meaning? I only know gray code is a binary numeral system where two successive values differ in only one bit.
Here is a solution online but I cannot understand this
private static int graycode(byte term1, byte term2) {
byte x = (byte)(term1^term2); // why use XOR?
int count = 0;
while(x!=0)
{
x = (byte)(x &(x-1)); // why use bitwise operator?
count++; // what is count?
}
return count == 1;
}
I try to understand spending a hour but I still do not have a clue.
Two numbers are considered consecutive in gray code if they differ by only one bit in their binary representation e.g. 111 and 101 differ by only the 2nd bit. The function you have checks if two input bytes have only one bit that makes them different. So 111 and 101 would return 1 from the function whereas 111 and 100 would return 0.
XOR is used to find differences between both numbers; XOR yields 1 when bits are different and 0 otherwise e.g. 1111 XOR 1011 would give 0100. So with XOR, each bit difference is highlighted by a 1 in that position. If both numbers are consecutive gray codes then there should be only one 1 in the XOR's result. More than one 1 would indicate multiple differences thus failing the criterion. The XOR result is stored in variable x.
The next task is then to count the number of 1's -- hence the variable count. If you try other gray code pairs (of greater bit length), you will notice the XOR value obtained will always be in this format (neglecting leading zeros): 10, 100, 1000, etc. Basically, 1 followed by zeros or, in other words, always a power of 2.
If these sample XOR results were decremented by 1, you would get: 01, 011, 0111, etc. If these new values were ANDed with the original XOR results, 0 would be the result everytime. This is the logic implemented in your solution: for a consecutive gray code pair, the while loop would run only once (and increment count) after which it would terminate because x had become 0. So count = 1 at the end. For a non-consecutive pair, the loop would run more than once (try it) and count would be greater than 1 at the end.
The function uses this as a basis to return 1 if count == 1 and 0 otherwise.
A bit obscure but it gets the job done.
It means the two numbers differ in exactly one bit.
So the solution begins with xor'ing the two numbers. The xor operation results in a 1 where the bits of the operands differ, else zero.
So you need to count the number of bits in the xor result and compare with 1. That's what your downloaded example does. This method of counting 1's in a binary number is a rather well-known method due to Brian Kernighan. The state x = (byte)(x & (x-1)) is bit magic that resets the highest order 1 bit to zero. There are lots of others.
Alternately you could search a table of the 8 possible bytes with 1 bit.
byte one_bit_bytes[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
It is a very non-intuitive way to count how many bits in a binary number are equal to '1'.
It requires a knowledge of binary arithmetic. Start with what happens when you subtract 1 for a decimal number which is written by a '1' followed by one or more zeroes: you get a sequence of 9's, which length is equal to the number of zeroes:
1000000 - 1 = 999999
A similar thing happens with binary numbers. If you subtract 1 from a non-negative binary number, all the lowest '0' digits are replaced by '1', and the '1' just before theses zeroes is replaced by zero. This follows from the way borrowing is done in binary. Example:
0101_0000_0001_0000 - 1 = 0101_0000_0000_1111
aaaa aaaa aaab cccc -> aaaa aaaa aaab cccc
Notation: Underscores to improve legibility. All the digits that appear above the letter a are unchanged. The digit '1' that appears above the letter b is changed to a '0'. And the digits '0' that appear above the letter c are changed to '1'.
The next step consists of doing a bitwise AND operation with the two numbers (X) and (X-1). With the arithmetic property described above, at each iteration there is exactly one '1' digit that disappear from the number (starting from the right, i.e. the least significant bit).
By counting the number of iterations, we can know how many '1' bits were initially present in number X. The iteration stops when the variable X equals zero.
Other people have already answered the question about gray code. My answer only explains how the "bit counting" works (after XOR'ing the two values).
Here is a naive test for a particular Gray code monotonic ordering (the binary reflected Gray code):
// convert Gray code binary number to base 2 binary number
int Base2(byte Gray){ Gray^=Gray>>4; Gray^=Gray>>2; return Gray^=Gray>>1; }
// test if Gray codes are consecutive using "normal" base 2 numbers
boolean GraysAdjacent(byte x, byte y){ return 1 == abs(Base2(x)-Base2(y)); }
see especially this answer (best):
How to find if two numbers are consecutive numbers in gray code sequence
coded in C as:
int GraysTouch(byte x, byte y){ return !( (x^y ^ 1) && ( x^y ^ (y&-y)<<1 ) ); }
// test x marks the spots! (where they touch!)
for(int i=31; i>-1; --i )
for(int j=31; j>-1; --j )
Serial.print((String)(GraysTouch( i^i>>1, j^j>>1 )?"x":".") +
(GraysTouch( j^j>>1, i^i>>1 )?"X":".") + (j?"":"\n"));
How this works: ... will be explained and not the OP code because it is highly suspect (see Caveats commentary below).
A property of XOR, aka the ^ operator, is that bits that match are 0 and bits that are different are 1.
1^0 == 0^1 == 1
1^1 == 0^0 == 0
Also, for a bit, 0 XOR b works as the identity function or simply b
and
1 XOR b works as the complement (no compliments please) function or ~b.
id(x) == x == x^0
opposite(x) == ~x == x^11111111 Why eight 1's? Are eight enough?
When comparing two bit strings with XOR, bits that are different XOR as 1, otherwise the bits must match and the XOR is 0 :
0101 0001111001100111000
XOR 0011 XOR 0001111001100000111
------ ---------------------
0110 0000000000000111111
This explains the x^y part of the code above.
----------------------------------------------------------------------
An aside:
n^n>>1 does a quick conversion from base 2 binary to the Gray code binary numbers used here.
Also note how potent it is that f(a,b)=a^b^b=a is idempotent for any b!
An in place swap is then a=a^b; b=a^b; a=a^b;.
Unrolled c=a^b; d=c^b; e=c^d; ie. d=a^b^b=a; e=a^b^a=b;
----------------------------------------------------------------------
Now, by definition, for two Gray coded numbers to be adjacent or consecutive there must be one and only one bit that can change and be different.
Examples:
Johnson
Code
000 000 000 000
001 001 001 100
011 101 011 110
111 111 010 010
110 011 110 011
100 010 111 111
110 101 101
100 100 001
^^^
this Gray coding
is the one used here
Examine it carefully.
Case 1
When the lowest order bit of consecutive numbers, x and y, for any of the Gray codes, are different, the rest must be the same! This is the definition of a Gray code. This means x^y must look like 0000...0001.
Remember complement, the ~ function aka 1^b? To test the last bit x^y is XOR'd with 1.
This explains the x^y ^ 1.
-------------------------------------------
Case 2
The location of the different bit in the consecutive Gray code numbers x and y is not the lowest order bit. Look carefully at these Gray code consecutive numbers.
001 010 101 lower order bits all match
011 110 111
| | | <-- | mark location of lowest 1
010 100 010 <-- XOR's
Interestingly, in this Gray code, when the lowest order bits match in x and y, so too does the location of the lowest order 1.
Even more interesting is that, for consecutive numbers, the bits are always different (for this Gray code) in the next higher order bit position!
So, x^y looks like ???...?1000...0 where 1000...0 must have at least one 0, 10 (Why?) and ???...? are the mystery bits that for consecutive Gray code numbers must be 000...0. (Why? ie. to be consecutive x^y must look like ... )
The observation is that
x^y looks like ???...?100...0 if and only if
x and y look like ???...?:10...0
| <-- remember? the 1 location !!
The | location can be found by either x&-x or y&-y. (Why? Why must the - be done using a 2's complement machine?)
However, the : location must be checked to see that it is 1 (Why?) and the ???...? are 000...0. (Why?)
So,
x^y looks like ???...?100...0 and
(y&-y)<<1 looks like 000...0100...0
and this explains the x^y ^ ((y&-y)<<1) test.
-------------------------------------------------------------------
Why this works: ... is a consequence of the properties of the particular Gray code used here. An examination and explanation is too complicated to be given here as to why this Gray code should have these properties.
----------------------------------------------------------------------
Commentary on the inadequacies of previous answers due to OP code issues.
Caveat 1: Just to be explicit, the algorithm in the OP's question:
private static int graycode(byte term1, byte term2) {
byte x = (byte)(term1^term2); // why use XOR?
int count = 0;
while(x!=0)
{
x = (byte)(x &(x-1)); // why use bitwise operator?
count++; // what is count?
}
return count == 1;
}
has an interesting interpretation of consecutive Gray codes. It does report correctly when any two binary sequences differ in a single bit position.
If, by consecutive codes it is meant that the Gray codes are used to enumerate a monotonic ordering, there is a problem.
Specifically, the code will return true for all these pairs:
000, 001 or 000, 010 or 000, 100
so an ordering might be 001, 000, 010 but then where can 100 go?
The algorithm reports (correctly) that the "consecutiveness" of 100 with either of 001 or 010 is false.
Thus 100 must immediately precede or follow 000 in an enumeration but cannot immediately precede or follow 001 or 010. DOH!!!
Caveat 2: Note x = (byte)(x & (x-1)) resets the lowest order 1 bit of x to zero.
refs:
Gray code increment function
Deriving nth Gray code from the (n-1)th Gray Code
https://electronics.stackexchange.com/questions/26677/3bit-gray-counter-using-d-flip-flops-and-logic-gates
How do I find next bit to change in a Gray code in constant time?
How to find if two numbers are consecutive numbers in gray code sequence
How it works the & Operator with numbers?
For example:
x = 8 & 4;
and the answer is 0.
How can i find the answer without using java or any other program?
You can find the answer without using Java converting the numbers into binary format:
4 = 0100
8 = 1000
If you perform an AND operation on each bit, you get:
0 & 1 = 0
1 & 0 = 0
0 & 0 = 0
0 & 0 = 0
That's why it's zero.
Java has three kinds of "AND" operators - the logical one, which is &&, a bitwise one, which is &, and a & on booleans, which does not short-circuit. Java compiler can distinguish between the kinds of operators by examining the type of the operands.
Bitwise operator takes binary representations of its operand, performs "AND" on each bit, and returns the result as a number.
For 4 and 8, bitwise "and" is zero, because they do not have 1 bits in common:
00000100 -- 8
00001000 -- 4
--------
& 00000000 -- 0
For other numbers, say, 22 and 5, the result would be different:
00010110 -- 22
00000101 -- 5
--------
& 00000100 -- 4
& is a bitwise and operator ... the binary values of 8 and 4 are
8 = 1000
4 = 0100
if you know how AND operator works then you know that
1 & 0 = 0;
so after a bitwise AND, there will be all 0
This question already has answers here:
What does the pipe character do in a Java method call?
(3 answers)
Closed 9 years ago.
Consider this following snippet:
input.setInputType(
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
What does the | do? I have never encountered that before in java.
It's a bitwise Or, if you have binary values it or's each of them together
00010110
10110000
---------
10110110
For each bit, the output will have a 0, if both of the corresponding input's bits have a 0. If either or both input's bits have a 1, it will output 1 in that slot.
It's kinda like an ||, except it checks on each individual bit, instead of the whole number.
In your case
The way your particular example what you're doing is encoding 2 conditions into a single value, has to do with masking.
Suppose InputType.TYPE_CLASS_TEXT was equal to 8 or 00001000
And suppose InputType.TYPE_TEXT_VARIATION_PASSWORD was equal to 32 or 00100000
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD would be equal to 00101000 or 40.
When you want to read them, you use bitwise anding. It's the exact opposite of oring. IT returns true only if both values are 1.
00010110
10110000
---------
00010000
To check if your value contains a result, you simply and it to the type
00101000 - 40 - Your result
00001000 - 8 - InputType.TYPE_CLASS_TEXT
--------
00001000 - 8 - this means that your result contains `InputType.TYPE_CLASS_TEXT`
in code, the check might look like this.
if(myInputType & InputType.TYPE_CLASS_TEXT != 0)
//myinput type cointains TYPE_CLASS_TEXT
Let's say you have some integer constants, W=1,X=2,Y=4,Z=8
The bit representations of these are:
0001
0010
0100
1000
You can "or" them together to request any combination of W/X/Y/Z and pass them as a single argument. Let's say I want features X and Y but not W and Z:
0010 | 0100 == 0110 (6)
So I call the function with (X | Y) and the function can bitwise-and the argument with the individual options (and test if != 0) to see which ones were selected:
0110 & W == 0000 == 0
0110 & X == 0010 != 0
0110 & Y == 0100 != 0
0110 & Z == 0000 == 0
Notice how I carefully selected the inputs to be all distinct powers of 2. This means the binary representation of each feature will always have just one unique bit set to "on" - which is key for making the whole flag-passing system work.
This is a bitwise or operator.
It's quite useful when you have a bunch of boolean flags you want to pass to a method to represent them as a single int, and "light" options by bitwise-oring between them.
In this case:
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
You'd be passing InputType.TYPE_CLASS_TEXT (=1) bitwise-or InputType.TYPE_TEXT_VARIATION_PASSWORD (=128), for a total of 129.
It's a bitwise OR operator. It's used to combine flag values into a single integer value that bitwise contains the true/false values of all the different flags.
It's basically to use a single integer as a list of true/false values.
In this case, imagine that InputType.TYPE_CLASS_TEXT has a value of 2 (or 10 in binary) and InputType.TYPE_TEXT_VARIATION_PASSWORD has a value of 4 ( or 100 in binary ).
The bitwise OR then combines 10 and 100 into 110, or 6. From the value 6 the calling code can then uniquely determine that both the flags TYPE_CLASS_TEXT and TYPE_TEXT_VARIATION_PASSWORD were passed to it.
Like it's already been mentioned, it's a bitwise OR operator. The idea is to save some memory and to store multiple flags within a single int.
I use the ~ operation for bit manipulation, and I'm just wondering how Java calculates the negative number?
I checked the Java documentation:
"The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111"."
So if int a = 60 (0011 1100), then int c = ~a (1100 0011).
The question is, how Java calculate negative numbers so that 1100 0011 = -61? The only way 1100 0011 is calculated -61 is
the highest bit is the sign bit.
-2^6 + 2^1 + 2^0 = -61.
But this make no sense to me.
The assumption that the highest bit is a simple sign bit is wrong. Java, as well as most modern programming languages (and hardware architectures) use the so-called two's complement representation for numbers. (The bit itself, coincidentally, does indicate the sign, but not in the way you would expect it to, i.e. 150 and -150 have more differences than just the sign bit in their representation.)
This representation might seem like an odd choice at first, but it actually makes operations such as adding a positive number to a negative number (or variations of this) automagically work, without making the processor have to check for special cases.
According to the relevant Wikipedia article:
The system is useful in simplifying the implementation of arithmetic on computer hardware. Adding 0011 (3) to 1111 (−1) at first seems to give the incorrect answer of 10010. However, the hardware can simply ignore the left-most bit to give the correct answer of 0010 (2). Overflow checks still must exist to catch operations such as summing 0100 and 0100.
The system therefore allows addition of negative operands without a subtraction circuit and a circuit that detects the sign of a number. Moreover, that addition circuit can also perform subtraction by taking the two's complement of a number (see below), which only requires an additional cycle or its own adder circuit. To perform this, the circuit merely pretends an extra left-most bit of 1 exists.
See this related answer for an even more in-depth explanation with lots of nice, easy to understand examples.
Java's primitive numeral data types - int, long, byte, and short are represented in two's complement. What this means:
The highest value is the result of all bits set to 1, save for the MSB.
Example: 0111 1111 = 127
The MSB being set to 1 and all other bits set to 0 is the lowest value.
Example: 1000 0000 = -128
The only negative value here is the MSB, so if we break it down into this representation, we'll arrive at -61:
|-128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
| 1 | 1 | 0 | 0 | 0 | 0 | 1 | 1 |
-128 + 64 + 2 + 1 = -61.