Calculating with xor variable - javascript

I do my calculations like this:
117^196
I get:
177
Now what I want to do is to get 117 back so I need to make a replace
(replace)^196 = 117
Whats the opposite operation from the xor operator?

The opposite of xor is xor :). If you xor something twice (a^b)^b == a.
This is relatively easy to show. For each bit:
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
Doing this on any pair of numbers a,b, it's easy to see that
a^b xor'd by either a or b yields the other (xor a yields b, and vice versa)
1 2 filter result
0^0^0 = 0
0^1^0 = 1
0^1^1 = 0
1^0^0 = 1
1^0^1 = 0
1^1^1 = 1

it's just xor it self.
like +'s opposite is -
xor's opposite is xor

Just use the result that you got: 177
117 ^ 196 = 177 | () ^ 196
117 ^ 196 ^ 196 = 177 ^ 196 | self-inverse
117 ^ 0 = 177 ^ 196 | neutral element
117 = 177 ^ 196
XOR has three important properties. It is
associative
commutative
self-inverse
This means that a value is its own inverse:
a^a = 0
Since it is also both commutative and associative, you can rearrange and xor-expression containing an event amount of the same operands like this:
a^O^b^c^O^d = O^O^a^b^c^d = 0^a^b^c^d = a^b^c^d
You could say that operands that appear an even amount of time "cancel each other out".

Related

bitwise operation of string and hex in javascript

How can I do bitwise operation between string and hexadecimal?
I need to use input of string to bitwise OR with hexadecimal and result should be hexadecimal.
First, input is string of time.
So 23:00 would be ["23", "00"].
Then I need it in hexadecimal as it is. For example, 23->0x23, 11->-0x11.
Now, bitwise OR with hexadecimal. But it doesn't give the result I want.
Expected result of (time[0] | 0x80) is 0xA3, where time[0] is 0x23 (0x isn't necessary)
Below is what I coded.
let input = "23:00"
let time = input.split(":"); //--> ["23","00"]
console.log(time[0] | 80); //--> 87
console.log(time[0] | "80"); //--> 87
console.log("0x"+time[0] | 80); //--> 115
console.log("0x"+time[0] | "0x80") //--> 163
you need to use proper radix in string2int2string conversions:
let input = "23:00"
let time = input.split(":"); //--> ["23","00"]
let temp = parseInt(time[0],16) | 0x80;
console.log(temp.toString(10)); // prints 163
console.log(temp.toString(16)); // prints a3

What is a ^ b and (a & b) << 1?

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.

Possible bug in Web Audio API AnalyserNode

I was playing around with Web Audio API and maybe found a bug in the AnalyserNode. Let's say I have two sine oscillators playing at different frequencies, 200 Hz and 8000 Hz respectively. Using two different AnalyserNode(s) I extract the non-zero frequency data from the two oscillators, which are the following (from chrome console):
OSC1 (200 Hz)
Bin 0 value 1
Bin 1 value 3
Bin 2 value 9
Bin 3 value 18
Bin 4 value 30
Bin 5 value 43
Bin 6 value 36
Bin 7 value 159
Bin 8 value 236
Bin 9 value 255
Bin 10 value 255
Bin 11 value 212
Bin 12 value 86
Bin 13 value 46
Bin 14 value 36
Bin 15 value 21
Bin 16 value 8
OSC2 (8000 Hz)
Bin 364 value 6
Bin 365 value 18
Bin 366 value 32
Bin 367 value 46
Bin 368 value 52
Bin 369 value 126
Bin 370 value 224
Bin 371 value 255
Bin 372 value 255
Bin 373 value 226
Bin 374 value 132
Bin 375 value 51
Bin 376 value 47
Bin 377 value 33
Bin 378 value 19
Bin 379 value 7
Now if I change the frequency value of the first oscillator to 8000 Hz (the same of the second oscillator) and extract again the non-zero frequency data I expect to obtain non zero values approximately in the same Bins of the second oscillator (say in the 300-400 range), but strangely there are non zero values also in the Bins in range 0-50 (as when we extracted frequency data using a 200 Hz frequency).
OSC1 (8000 Hz)
Bin 2 value 2
Bin 3 value 11
Bin 4 value 23
Bin 5 value 36
Bin 6 value 29
Bin 7 value 152
Bin 8 value 229
Bin 9 value 255
Bin 10 value 248
Bin 11 value 205
Bin 12 value 79
Bin 13 value 38
Bin 14 value 29
Bin 15 value 14
Bin 16 value 1
Bin 364 value 7
Bin 365 value 19
Bin 366 value 33
Bin 367 value 47
Bin 368 value 50
Bin 369 value 137
Bin 370 value 228
Bin 371 value 255
Bin 372 value 255
Bin 373 value 222
Bin 374 value 121
Bin 375 value 52
Bin 376 value 45
Bin 377 value 31
Bin 378 value 18
Bin 379 value 5
Is this the expected behavior or a bug? It seems not correct to me. I am also not sure if this propagates also when analyzing a standard audio file using for example a requestAnimationFrame loop.
Below the code of the full example.
NB: to extract the frequency data is required to wait a bit before the analyser has finished the Fast Fourier Transform algorithm and the frequency data is available, thus I've used 2 timeOut functions, one for the first extraction of frequency data from osc1 and osc2 and the second to extract again frequency data from osc1 after the oscillator frequency has changed to 8000 Hz).
var AudioContext = window.AudioContext || window.webkitAudioContext;
var ctx = new AudioContext();
// first oscillator (200 Hz)
var osc1 = ctx.createOscillator();
osc1.frequency.value = 200;
var analyser1 = ctx.createAnalyser();
var gain1 = ctx.createGain();
gain1.gain.value = 0;
osc1.connect(analyser1);
analyser1.connect(gain1);
gain1.connect(ctx.destination);
// second oscillator (8000 Hz)
var osc2 = ctx.createOscillator();
osc2.frequency.value = 8000;
var analyser2 = ctx.createAnalyser();
var gain2 = ctx.createGain();
gain2.gain.value = 0;
osc2.connect(analyser2);
analyser2.connect(gain2);
gain2.connect(ctx.destination);
// start oscillators
osc1.start();
osc2.start();
// get frequency data
var freqData1 = new Uint8Array(analyser1.frequencyBinCount);
var freqData2 = new Uint8Array(analyser2.frequencyBinCount);
setTimeout(function() {
analyser1.getByteFrequencyData(freqData1);
analyser2.getByteFrequencyData(freqData2);
console.log("OSC1 (200 Hz)");
printNonZeroFreqData(freqData1);
console.log("OSC2 (8000 Hz)");
printNonZeroFreqData(freqData2);
// change frequency of osc1 to 8000 Hz
osc1.frequency.value = 8000;
// wait a bit, then extract again frequency data from osc1
setTimeout(function() {
freqData1 = new Uint8Array(analyser1.frequencyBinCount);
analyser1.getByteFrequencyData(freqData1);
console.log("OSC1 (8000 Hz)");
printNonZeroFreqData(freqData1);
}, 500);
}, 500);
// print non zero frequency values
function printNonZeroFreqData(arr) {
for (var i = 0; i < arr.length; ++i) {
if (arr[i] != 0) {
console.log("Bin " + i, "\tvalue " + arr[i]);
}
}
console.log("");
}
This is expected. According to the spec, successive calls to extract the frequency data combines the data from the current call with a history of the data from previous calls. If we want to see the frequency data only from the current time, set smoothingTimeConstant to 0.
smoothingTimeConstant on Mozilla Developer Network

JavaScript - Negative byte from integer

I transmit a byte that's always less than 127 with a 1 bit flag to the client by ORing the byte with 0x80.
On the client side, in JavaScript, I have an Array() of numbers representing the bytes of the message (yes it's probably dumb but I haven't figured out typed arrays yet).
Everything works fine until I hit a number with the highest bit of the lowest byte set.
Number: 0011 0101
flag: 1000 0000
---------
1011 0101
Stored as
integer in ???
JavaScript
How can I retrieve the original byte (with the highest bit set to 0), plus the flag (denoted by the value of the highest bit)?
EXAMPLE:
(server)
byte x = 90
x | 0x80
> -38
(client - JavaScript)
var x = -38
x ^ 0x80
> -166
How do I get 90 back?
EDIT - I discovered this was due to another bug in my code... I wasn't going crazy with the encoding... sorry all...
Try the following in JavaScript:
var received = -38;
var adjusted = received & 0xFF; // 218
var original = adjusted ^ 0x80; // 90
That should solve your problem.
Explanation: All numbers in JavaScript stored in the double-precision floating point format:
Bitwise operators however can't deal with floating point numbers. Hence they convert their operands into 32-bit signed integers. [source]
-38 = 11111111 11111111 11111111 11011010
Hence if you do -38 ^ 0x80 you get the wrong answer as only the 8th bit from the right is set to 0. You need to first limit -38 to 8-bits before xoring it with 0x80. Only the least significant byte (i.e. 11011010) is needed. Hence we do -38 & 0xFF to get the least significant byte.
Now that you have the correct byte you may simply xor it with 0x80.
TLDR: Use byte & 0xFF ^ 0x80.
Not sure I understand the question, but I will give a shot: you have just to XORing the 0x80:
var received = 181; // 10110101
var num = received ^ 0x80;
console.log(num); // 53, 00110101
If you have a different result, probably there is something different in your code – if you run the code above, should give the expected result.
I'm not seeing a problem.
Here is some code I've written to test, with JSFiddle live demo
var val = 57;
var flag = 1;
var valWithFlag = val | (flag ? 0x80 : 0);
var newVal = (valWithFlag & 0x7F);
var newValFlag = (valWithFlag & 0x80 ? 1 : 0);
alert("Val: " + val.toString() + "\n" +
"Flag: " + flag.toString() + "\n" +
"Val With Flag: " + valWithFlag.toString() + "\n" +
"New Val Without Flag: " + newVal.toString() + "\n" +
"New Val Flag: " + newValFlag.toString() + "\n");
It is giving the desired results...
Val: 57
Flag: 1
Val With Flag: 185
New Val Without Flag: 57
New Val Flag: 1
UPDATE based on extra details provided by the OP
I think this is probably due to integers in javascript being held either as 32 or 64 bit values... so when you pass through -38 to javascript it isn't being held in the same way as the single byte on your server.
You need to convert that -38 into an 8-byte...
var val = -38;
var jsVal = (val & 0xFF);
Which should give you your 90 value to work with. Here is an updated JSFiddle

What does the ^ (caret) symbol do in JavaScript?

I have some JavaScript code:
<script type="text/javascript">
$(document).ready(function(){
$('#calcular').click(function() {
var altura2 = ((($('#ddl_altura').attr("value"))/100)^2);
var peso = $('#ddl_peso').attr("value");
var resultado = Math.round(parseFloat(peso / altura2)*100)/100;
if (resultado > 0) {
$('#resultado').html(resultado);
$('#imc').show();
};
});
});
</script>
What does the ^ (caret) symbol mean in JavaScript?
The ^ operator is the bitwise XOR operator. To square a value, use Math.pow:
var altura2 = Math.pow($('#ddl_altura').attr("value")/100, 2);
^ is performing exclusive OR (XOR), for instance
6 is 110 in binary, 3 is 011 in binary, and
6 ^ 3, meaning 110 XOR 011 gives 101 (5).
110 since 0 ^ 0 => 0
011 0 ^ 1 => 1
--- 1 ^ 0 => 1
101 1 ^ 1 => 0
Math.pow(x,2) calculates x² but for square you better use x*x as Math.pow uses logarithms and you get more approximations errors. ( x² ~ exp(2.log(x)) )
Its called bitwise XOR. Let me explain it:
You have :
Decimal Binary
0 0
1 01
2 10
3 11
Now we want 3^2= ?
then we have 11^10=?
11
10
---
01
---
so 11^10=01
01 in Decimal is 1.
So we can say that 3^2=1;
This is the bitwise XOR operator.
The bitwise XOR operator is indicated
by a caret ( ^ ) and, of course, works
directly on the binary form of
numbers. Bitwise XOR is different from
bitwise OR in that it returns 1 only
when exactly one bit has a value of 1.
Source: http://www.java-samples.com/showtutorial.php?tutorialid=820

Categories