What does this JavaScript code mean?
flag &= ~CONST
Is it append, prepend, intersection or something else?
Look at Bitwise operators.
& Operator
& puts 1 where both operands' bits are 1.
Example
10000001 & 00000001 = 00000001
~ Operator
~ inverts the bits.
Example
~10000000 = 011111111;
flag &= ~CONST is short hand for flag = flag & ~CONST;.
You may have seen something similar, e.g. number *= 10.
This will turn off whatever constant represents.
For example, lets look at a hypothetical example of code which would represent the state of a window:
WS_HASBORDER = 0x01;
WS_HASCLOSEBUTTON = 0x02;
WS_HASMINIMIZEBUTTON = 0x04;
WS_HASMAXIMIZEBUTTON = 0x08;
WS_ISMAXIMIZED = 0x10;
We could represent the "state" of the window by using
windowState = WS_HASBORDER | WS_HASCLOSEBUTTON | ... etc
now, lets say we want to "turn off" one of these states, well, thats what your example code does...
windowState &= ~WS_HASBORDER
Now what the above code does, is it gets the compliment [i guess you could call it the inverted bits] of whatever is to its right, WS_HASBORDER.
So.. WS_HASBORDER has one bit turned on, and everything else is turned off. Its compliment has all bits turned on, except for the one bit that was turned off before.
Since I've represented the many constants as bytes, i'll just show you an example [not that javascript doesn't represent numbers as bytes, nor can you do so]
WS_HASBORDER = 0x01; //0000 0001
WS_HASCLOSEBUTTON = 0x02; //0000 0010
WS_HASMINIMIZEBUTTON = 0x04; //0000 0100
WS_HASMAXIMIZEBUTTON = 0x08; //0000 1000
WS_ISMAXIMIZED = 0x10; //0001 0000
_ now for an example
windowState = WS_HASBORDER | WS_HASCLOSEBUTTON | WS_HASMINIMIZEBUTTON |
WS_HASMAXIMIZEBUTTON | WS_ISMAXIMIZED;
0000 0001
0000 0010
0000 0100
0000 1000
and) 0001 0000
--------------
0001 1111 = 0x1F
So... windowState gets the value 0x1F
windowState &= ~ WS_HASMAXIMIZEBUTTON
WS_HASMAXIMIZEBUTTON: 0000 1000
~WS_HASMAXIMIZEBUTTON: 1111 0111
..To finish our calculation
windowState
&) ~WS_HASMAXIMIZEBUTTON
becomes
0001 1111
&) 1111 0111
-------------
0001 0111 = 0x07
Here are your resulting flags:
On:
WS_HASBORDER
WS_HASCLOSEBUTTON
WS_HASMINIMIZEBUTTON
WS_ISMAXIMIZED
Off:
WS_HASMAXIMIZEBUTTON
Hope that helps. Back to procrastinating homework I go! haha.
Related
I want to generate UniqueID for objects, by generating the character part of the UniqueID from ASCII values, without declaring any Arrays, The Unique ID should start from AA01 and continue through AA99, then AB01 through AB99, then AC01 though AC99, AD01 -> AD99, -> AE01 -> AE99 ..and so on. I also need to apply padding, so the UniqueID always has 4 values like "AC08" instead of "AC8".
Below is a snippet of what I have done.
function genUID (a,b){
var res="";
var res2="";
var res3;
if (a=>65 && a<=90) {
res = String.fromCharCode(a);
if(b=>65 && b<=90) {
res2= String.fromCharCode(b); b++;
for(c=1;c<150;c++){
if(c<100){
(res3=c);
}
else {
(res3= c-99); }
console.log(res+""+res2+""+res3);
}
a++ }
} }
Are you not making this way more complicated than it needs to be? Just increase a normal number, format it to four digits length by padding zeroes on the left - and then just “translate” the first two numeric digits to their character “equivalent”, by adding the difference between the character codes for A and 0 ...
for(var i=1; i<3000; ++i) {
var padNum = ("000"+i).substr(-4),
uniqID =
String.fromCharCode(padNum.charCodeAt(0)+17) +
String.fromCharCode(padNum.charCodeAt(1)+17) +
padNum[2] +
padNum[3];
console.log(padNum, uniqID)
}
Result: (Snippet console here does not show the full result, but only the last few lines)
0001 AA01
0002 AA02
0003 AA03
0004 AA04
0005 AA05
0006 AA06
0007 AA07
0008 AA08
0009 AA09
0010 AA10
0011 AA11
...
0099 AA99
0100 AB00
0101 AB01
0102 AB02
...
0199 AB99
0200 AC00
0201 AC01
0202 AC02
...
0998 AJ98
0999 AJ99
1000 BA00
1001 BA01
1002 BA02
...
I was doing this question in leetcode.
Request:
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
I can't understand the solution it gave
Could someone explain how this getSum function works?
Here is the answer in JS:
var getSum=function(a,b) {
const Sum = a^b; //I can't understand how those two line's code can
const carry = (a & b) << 1; //get the sum
if(!carry) {
return Sum
}
return getSum(Sum,carry);
};
console.log(getSum(5,1));
It's basically replicating the half-adder
Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below
╔═══════╤═════════════╗
║ Input │ Output ║
╠═══╤═══╪═══════╤═════╣
║ A │ B │ carry │ sum ║
╟───┼───┼───────┼─────╢
║ 0 │ 0 │ 0 │ 0 ║
╟───┼───┼───────┼─────╢
║ 1 │ 0 │ 0 │ 1 ║
╟───┼───┼───────┼─────╢
║ 0 │ 1 │ 0 │ 1 ║
╟───┼───┼───────┼─────╢
║ 1 │ 1 │ 1 │ 0 ║
╚═══╧═══╧═══════╧═════╝
From the table we get the logic for the outputs: carry = A and B, sum = A xor B
XOR is also called a carry-less add operator, and represented by ⊕ with the + symbol inside
So the snippet above is working like this
const Sum=a^b; // sum = a xor b = a ⊕ b
const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
if(!carry){
return Sum; // no carry, so sum + carry = sum
}
return getSum(Sum,carry); // a + b = sum + carry
So a^b adds each bit in a and b simultaneously, leaving the non-carry sum of a and b in Sum. Then we have to add carry to the carry-less sum to get the final result, since we have only a half-adder instead of a full-adder which does a + b = a ⊕ b + carry
See also
Adding two numbers without + operator (Clarification)
What is the best way to add two numbers without using the + operator?
adds two numbers without using + or any arithmetic operators
Adding two numbers without using the addition operator
Let's learn by example. Imagine that a = 3 and b = 5
In binary notation they are a = 0011 and b = 0101
XOR:
a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11
So when we're doing a^b result will be 0110.
AND + SHIFT
a&b performs logical AND operation. It returns 1 only when a = b = 1.
In our case the result is 0001
<< shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).
Next iterations:
Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)
Now a^b = 0100 and (a&b)<<1 = 0100
Repeating again.
Now a^b = 0000 and (a&b)<<1 = 1000
And again.
Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.
Everything worked fine since 3+5=8
int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
int carry = (p & q) << 1; // Left Shift, 1+1=2
if (carry != 0) {
return getSum(result, carry);
}
return result;
Start By p=5,q=6. Then the XOR would be,
0101
0110
------
0011
So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,
0101
0110
-------
0100
We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get
0100<<1=1000
So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.
getSum(3, 8);
So, doing the first XORing we get,
0011
1000
-------
1011
The XORing this time yielded in 11 (1011 binary),so we perform the AND now,
0011
1000
-------
0000
We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).
Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.
^ is XOR, a bitwise operation. On a single bit, the rules are 0 ^ 0 = 0, 0 ^ 1 = 1, 1 ^ 0 = 0, and 1 ^ 1 = 0, and you simply extend perform it on corresponding bits when dealing with multi-bit values. The name is short for "exclusive or", and comes from the fact that A ^ B is 1 if and only if either A or B is 1, not both. But, it's more interesting to talk about its other name, ⊕. ⊕ is + but slightly different. You'll notice that the rules for ⊕ are similar to the rules for addition: 0 + 0 = 0, 0 + 1 = 1, 1 + 0 = 1, and 1 + 1 = 10. ⊕ is +, except 1 ⊕ 1 = 0; that is, ⊕ is +, except without carrying. This holds for multiple bits: 011 + 001 = 100, because you carry a 1 out of the ones place into the twos place, and then carry a 1 again into the fours place. Then, 011 ⊕ 001 = 010, because you just don't carry.
Now, when doing real addition, when do you carry? In binary, the answer is very simple: you carry a 1 into the next place when there are two 1s in a given place. This is easily understood as a bitwise AND, &. 1 & 1 = 1, and 0 otherwise. For 011 + 001, addition without carrying gives 011 ⊕ 001 = 010, and we can tell we need to carry a 1 out of the ones place because 011 & 001 = 001. The shifting in (a & b) << 1 turns a number "where do I need to carry from?" into "where do I need to add carries?": (011 & 001) << 1 = 010; I need to add a carry bit in the twos place.
So, in getSum, we want to know a + b. We compute the addition without carrying with a ^ b, and we find where we need to add carry bits with (a & b) << 1. Now, we just need to add those two together. Well, we already have a function for adding numbers together; it's called getSum. So, we basically just write function getSum(a, b) { return getSum(a ^ b, (a & b) << 1); }, except we make sure to short-circuit if there is nothing to carry, saving us from infinite recursion.
I'm reading this explanation of DataView and there's an example there:
var littleEndian = (function() {
var buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
// Int16Array uses the platform's endianness.
return new Int16Array(buffer)[0] === 256;
})();
I don't really understand what this line does:
new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
Does it mean that the data stored in the range [0;256] bits should be stored in littleEndian?
Suppose we create an array buffer and array like this:
var dv = new DataView(new ArrayBuffer(4));
It means that we've got 32 bits in memory:
0000 0000 0000 0000 0000 0000 0000 0000
Now, we want to store the number 0x0103, which has the pattern:
0000 0001 0000 0011
Now, let's store this number in first two bytes using little endianess, and in the second two bytes using big endianess and see how it's laid out in the memory. So:
dv.setInt16(0, 0x0103, true);
dv.setInt16(2, 0x0103, false);
Now, the bits in the DataView have this pattern:
0000 0011 0000 0001 0000 0001 0000 0011
Here is the code to test that behavior:
var little = dv.getUint16(0);
little === 0x0103 // false
little === 0x0301 // true
var big = dv.getUint16(2);
big === 0x0103 // true
big === 0x0301 // false
This question already has answers here:
What does a tilde do when it precedes an expression?
(5 answers)
Closed 8 years ago.
I see sometimes the symbol ~ in code. I tried it with ~1, and it shows 0.
And thus, I can see some code using this trick:
if ( !~text.indexOf('a') ){ }
To check for truthy value. Is it kind of bit shifting?
It's the bitwise NOT operator. It will convert the operand to an 32-bit integer, then yields one's complement (inverts every bit) of that integer.
Finally, ! will return true if and only only if the result of that operation is 0.
Some examples might help:
x | x (bin) | ~x (bin) | ~x | !~x
-3 | 1111…1101 | 0000…0010 | 2 | false
-2 | 1111…1110 | 0000…0001 | 1 | false
-1 | 1111…1111 | 0000…0000 | 0 | true
0 | 0000…0000 | 1111…1111 | -1 | false
1 | 0000…0001 | 1111…1110 | -2 | false
In other words,
if ( !~text.indexOf('a') ) { }
is equivalent to:
if ( text.indexOf('a') == -1 ) { }
~ is the bitwise negation operator[MDN]. It converts its operand to a 32-bit integer and swaps all the 1s to 0s and all the 0s to 1s.
For example:
0000 0000 0000 0000 0000 0000 0000 0000 = 0
1111 1111 1111 1111 1111 1111 1111 1111 = ~0 = -1
Instead of doing text.indexOf(str) !== -1) you can use the tricky !~text.indexOf(str), because ~1 === 0 and !0 === true.
~ is the unary negation operator. Basically converts the operand to a 32-bit integer and then flips every bit of the integer.
~12 =
~(00000000 00000000 00000000 00001100) =
(11111111 11111111 11111111 11110011) =
-13
I'm looking for a lossless compression algorithm (like LZW or Huffman or anything) in javascript, that accepts and returns raw, binary data.
With 'binary data' I mean a sequence of bytes, which may come in any of the following forms:
a string containing characters with any value from 0 to 255
an array containing integers with any value from 0 to 255
a string containing a hexadecimal representation of the data (i.e. 2 hex digits per byte)
a string containing the base64 encoded representation of the data
or anything else that can be unambiguously converted from or to any of the above
Now obviously there are TONS of javascript implementations available everywhere, for a wide range of algorithms. However EVERYTHING I find seems to do crazy stuff like:
returning an array containing also values >255 (so what is the compression ratio now? how do I represent this in bytes, or how would I go about saving this to a file for example?)
messing with character encodings in strings, converting from/to unicode or url/html entities or whatnot (it's BINARY, character encoding does not apply here!)
return other representations that don't seem suitable for binary storage (i.e. cannot be converted to sequence of bytes)
Would anyone know of a good javascript compression (+decompression) implementation that suits my binary fetish?
I think I found what I was looking for after all: this deflate + inflate implementation in javascript seems to work with strings as byte sequences.
first of all create a closure for hold the binar or hex or decimal flags
function ASearch() { }
ASearch.Flag = {
Front_Wheel_Drive: 0xF, Rear_Wheel_Drive: 0xF0, Four_Wheel_Drive: 0xF00,
Auto: 0xFF, Manual: 0xFF00,
Gas: 0xF, Diesel: 0xF0, Hybrid: 0xF00, Electrical: 0xF000,
Two: 1, Three: 2, Four: 4, Five: 8, Six: 16, Eight: 32, Ten: 64, Twelve: 128
};
then set like this
SetFlag = (function (e) {
e = e.srcElement;
$("#" + e.parentNode.name).val(e.checked ?
$("#" + e.parentNode.name).val() | ASearch.Flag[e.id] :
$("#" + e.parentNode.name).val() ^ ASearch.Flag[e.id]);
});
this is an example for packed data in a 32 bit integer
there are four variable... i've used them for 18 flags.. this is fast and super effective
for example...
int i = 0; //binary = 0000 0000 0000 0000
i = i | 255; //binary = 0000 0000 1111 1111
i = i ^ 255; //binary = 0000 0000 0000 0000
i = i | 0xFF00; //binary = 1111 1111 0000 0000
i = i | 255; //binary = 1111 1111 1111 1111
i = i ^ 0xFF00; //binary = 0000 0000 1111 1111