Signed to Unsigned and Vice Versa (arithmetical) - javascript

How to convert a number from unsigned to signed?
signed: -32768 to 32767
unsigned: 0 to 65535
I am solving the problem in JavaScript. The situation is that I have a number that goes e.g. from 0 to 65535 and I want to convert it to a reasonable signed value.
e.g.: 65535 should become -1.
Please do not use any bit related operations but something arithmetical.
I guess this should be language independent assuming that we use a data type that is big enough.
Update:
Implementation according to the answer further down:
function convertWordToShort(ival) {
if (isNaN(ival) === false) {
if (ival > 32767) {
ival = ival - 65536;
}
}
return ival;
}
function convertShortToWord(ival) {
if (isNaN(ival) === false) {
if (ival < 0) {
ival = ival + 65536;
}
}
return ival;
}
function convertIntToDWord(ival) {
if (isNaN(ival) === false) {
if (ival < 0) {
ival = ival + 4294967296;
}
}
return ival;
}
function convertDWordToInt(ival) {
if (isNaN(ival) === false) {
if (ival > 2147483647) {
ival = ival - 4294967296;
}
}
return ival;
}

Just test if the number is over halfway, then subtract the modulus.
if(x > 32767) {x = x - 65536;}

In the case that you would be looking for bitwise operation related answers, you could try the following:
to convert something akin to a 16 bit unsigned integer (i.e 0 <= n <= 65535) to a 16 bit signed one:
(number << 16) >> 16
Or:
new Int16Array([number])[0]
Where number in both cases is your 16 bit number.
As a side note the reason the first solution works is because if you bit shift to the right 16 times, the most significant bit of your 16 bit number will actually become the most significant bit of the 32 bit JavaScript integer (so if the most significant bit was a 1, it'd make the number negative), and so when you shift it to the left 16 times it'd shift while keeping the standard 2s complement form and retain the value/sign it gained from being shifted to the right previously, see this Wikipedia article for more:
https://en.m.wikipedia.org/wiki/Arithmetic_shift

function signed(bits, value) { return value & (1 << (bits - 1)) ? value - (1 << bits) : value; }
signed(8, 0xFF); // returns -1
signed(16, 0xFF); // returns 255

Related

Reverse Bits JavaScript

The problem is standard but the solution in JavaScript takes a lot more effort to code.
I got the solution but my answer is coming half of what is desired.
Problem Description
Reverse the bits of a 32-bit unsigned integer A.
Problem Constraints
0 <= A <= 2^32
Input Format
The first and only argument of input contains an integer A.
Output Format
Return a single unsigned integer denoting minimum xor value.
Example Input
Input 1:
0
Input 2:
3
Example Output
Output 1:
0
Output 2:
3221225472
My solution
function modulo(a, b) {
return a - Math.floor(a/b)*b;
}
function ToUint32(x) {
return modulo(parseInt(x), Math.pow(2, 32));
}
function revereBits(A){
A = A.toString(2);
while (A.length < 31){
A = "0"+A;
}
var reverse = 0;
var NO_OF_BITS = A.length;
for(var i = NO_OF_BITS; i >= 1; i--){
var temp = (parseInt(A, 2) & (1 << i - 1));
if(temp){
reverse |= 1 << (NO_OF_BITS - i);
}
}
if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);
return reverse;
}
Now, in the line
if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);
You see that I have to double the answer. I cannot, however, get the part of why is this required.
I took the approach from https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/
Had to make few adjustments to it. For example, run the loop from 31 to 1 rather than 0 to 31. The latter gives negative values in first left shift operation for i = 0 itself.
Can someone please help in fixing this solution and point to the problem in this?
UPDATE - Problem is related to Bit manipulation. So guys, please don't answer or comment for anything consisting of in-built string functions of Javascript. Cheers!
You should be able to do it using just bitwise operators, and a typed array to solve the sign issue:
Update
Changing slightly approach of the rev function after #bryc comment. Since having multiple function for "history" purpose makes the answer difficult to read, I'm putting first the latest code.
However, I'm keeping the comments about the different steps – the rest can be found in the edit history.
function rev(x) {
x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);
x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);
x = ((x >> 4) & 0x0F0F0F0F) | ((x & 0x0F0F0F0F) << 4);
x = ((x >> 8) & 0x00FF00FF) | ((x & 0x00FF00FF) << 8);
x = (x >>> 16) | (x << 16);
return x >>> 0;
}
This is the same code you would write in other languages as well to reverse bits, the only difference here is the addition of the typed array.
As #harold pointed out in the comment, the zero-fill right shift returns an unsigned (it's the only bitwise operator to do so) therefore we can omit the typed array and just add >>> 0 before the return.
In fact, doing >>> 0 is commonly used to simulate the ToUint32 in JS polyfilll; e.g.:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
// 2. Let lenValue be the result of calling the Get internal method
// of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
function reverseBits(integer, bitLength) {
if (bitLength > 32) {
throw Error(
"Bit manipulation is limited to <= 32 bit numbers in JavaScript."
);
}
let result = 0;
for (let i = 0; i < bitLength; i++) {
result |= ((integer >> i) & 1) << (bitLength - 1 - i);
}
return result >>> 0; // >>> 0 makes it unsigned even if bit 32 (the sign bit) was set
}
Try this:
function reverseBits(num) {
let reversed = num.toString(2);
const padding = "0";
reversed = padding.repeat(32 - reversed.length) + reversed;
return parseInt(reversed.split('').reverse().join(''), 2);
}
console.log(reverseBits(0)); // 0
console.log(reverseBits(3)); // 3221225472

Do you know of a computer algorithm to solve the ability to divide without division operators?

Through applying a computer science algorithm in JavaScript, could you solve the following question?
The function accepts a numerator and denominator in the form of a positive or negative integer value.
You can not use '*', '/' or '%'.
function divide(num, denom) {
// ...
}
divide(6, 2)
divide(-10, 5)
divide(7, 2)
divide(-5, 10)
I am curious to know if there is a known computer science algorithm out there that can solve this.
I saw this question and had to take a crack at it, I've implemented a solution that can get decimal places up to a specified precision as well as handle negatives, it uses a recursive approach and some string manipulation.
// Calculate up to decimal point
const MAX_PRECISION = 6;
function divide(numerator, denominator, answer=0, decimals=MAX_PRECISION)
{
// Account for negative numbers
if ((numerator < 0 || denominator < 0))
{
// If both are negative, then we return a positive, otherwise return a negative
if (numerator < 0 && denominator < 0)
return divide(Math.abs(numerator), Math.abs(denominator))
else return -divide(Math.abs(numerator), Math.abs(denominator));
}
// Base case return if evenly divisble or we've reached the specificed percision
if (numerator == 0 || decimals == 0) return answer;
// Calculate the decimal places
if (numerator < denominator)
{
// Move the decinal place to the right
const timesTen = parseInt(numerator + "0");
// Calcualte decimal places up to the certain percision
if (decimals == MAX_PRECISION)
return parseFloat(answer + "." + divide(timesTen, denominator, 0, decimals-1));
else return answer + "" + divide(timesTen, denominator, 0, decimals-1);
}
// Perform the calculations in a tail-recursive manor
return divide(numerator-denominator, denominator, answer+1, decimals);
}
// Test Cases
console.log(divide(10, 2));
console.log(divide(10, -2));
console.log(divide(-7, -4));
console.log(divide( 1, -2));
console.log(divide(11, 3));
console.log(divide(22, 7));
You can try Something like:
function divide(num, denom) {
var count = 0;
while (num > 0) {
num = num - denom
if (num >= 0) {
count ++;
}
}
return count;
}

Javascript get single bit

I have an integer and i want to check if a single bit is 0 or 1.
What is the best practise for doing that?
An example of what i'm doing at this moment:
const myInt = 8; // Binary in 32 Bit integer = 00000000000000000000000000001000
const myBit = myInt << 28 >>> 31; // 00000000000000000000000000000001
if (myBit === 1) {
//do something
}
But i think that this isn't the best methode for doing this.
Have you any better idea?
EDIT:
It is always the same bit i want to check, but the integer is different
myInt = 8+4; // 1100
n = 3;
(myInt >> n) & 0x1; // 1
n = 2;
(myInt >> n) & 0x1; // 1
n = 1;
(myInt >> n) & 0x1; // 0
n = 0;
(myInt >> n) & 0x1; // 0
general solution shifts your number by N bits to right, and applies bitmask, that leaves only last bit, all other are set to 0
I think you can use the bitwise AND
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
my32Bit = 123414123;
twoBy7 = 128;
//check the 7th bit
if (my32Bit & twoBy7) {
// should return 1 if the 7thbit is 1
}
You could take the bit and a left shift << with bitwise AND & operator.
var value = 10,
bit;
for (bit = 0; bit < 4; bit++) {
console.log(bit, !!(value & (1 << bit)));
}

What is the best way to determine if a given number is a power of two?

Is there a more effective way to return true if n is a power of two or false if not?
function isPowerOfTwo(n) {
return Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
}
You can actually use ECMAScript5 Math.log:
function powerOfTwo(x) {
return (Math.log(x)/Math.log(2)) % 1 === 0;
}
Remember, in math, to get a logarithm with an arbitrary base, you can just divide log10 of the operand (x in this case) by log10 of the base. And then to see if the number is a regular integer (and not a floating point), just check if the remainder is 0 by using the modulus % operator.
In ECMAScript6 you can do something like this:
function powerOfTwo(x) {
return Math.log2(x) % 1 === 0;
}
See the MDN docs for Math.log2.
Source: Bit twiddling Hacks,
function powerOf2(v) {
return v && !(v & (v - 1));
}
You just bitwise AND the previous number with the current number. If the result is falsy, then it is a power of 2.
The explanation is in this answer.
Note:
This will not be 100% true for programming, mathematical, [also read 'interviewing']. Some edge cases not handled by this are decimals (0.1, 0.2, 0.8…) or zero values (0, 0.0, …)
Using bitwise operators, this is by far the best way in terms of efficiency and cleanliness of your code:
function PowerofTwo(n){
return ((x != 0) && !(x & (x - 1)));
}
what it does is checks the bits that make up the number, i.e. 8 looks like this:
1 0 0 0
x-1 or 7 in this case looks like this
0 1 1 1
when the bitwise operator & is used it invokes an && on each bit of the number (thus 1 & 1 = 1, 1 & 0 = 0, 0 & 1 = 0, 0 & 0 = 1):
1 0 0 0
-0 1 1 1
=========
0 0 0 0
since the number turns into an exact 0 (or false when evaluted as a boolean) using the ! flag will return the correct answer
if you were to do this with a number like 7 it would look like this:
0 1 1 1
-0 1 1 0
=========
1 1 1 0
returning a number greater than zero causing the ! flag to take over and give the correct answer.
A number is a power of 2 if and only if log base 2 of that number is whole. The function below computes whether or not that is true:
function powerOfTwo(n){
// Compute log base 2 of n using a quotient of natural logs
var log_n = Math.log(n)/Math.log(2);
// Round off any decimal component
var log_n_floor = Math.floor(log_n);
// The function returns true if and only if log_n is a whole number
return log_n - log_n_floor == 0;
}
Making use of ES6's Math.clz32(n) to count leading zeros of a 32-bit integer from 1 to 2³² - 1:
function isPowerOf2(n) {
return Math.clz32(n) < Math.clz32(n - 1);
}
/**
* #param {number} n
* #return {boolean}
*/
const isPowerOfTwo = function(n) {
if(n == 0) return false;
while(n % 2 == 0){
n = n/2
}
return n === 1
};
function PowerOfTwo(n){
// Exercise for reader: confirm that n is an integer
return (n !== 0) && (n & (n - 1)) === 0;
}
console.log(PowerOfTwo(3))
console.log(PowerOfTwo(4))
This is for a specific online course that requires an answer in a specific way.
Without using libraries and other methods just loops and .push.
you need to create an inner loop using while
it should start with 1
keep multiplying it with 2 until i,j,k or whatever is greater than the current number(array) so it will have to do 2 4 6 8 10 12 14 16 18 until it is greater than the number
then it will go to the outer loop then repeat again until
const numbers = [5, 3, 9, 30];
const smallestPowerOfTwo = arr => {
let results = new Array;
// The 'outer' for loop -
for (let i = 0; i < arr.length; i++) {
number = arr[i];
// The 'inner' while loop
j = 1;
while (j < number) { //starting from 1 then multiplied by 2 then by 2 again untill it is more than the number
j = j * 2;
}
results.push(j);
}
return results
}
console.log(smallestPowerOfTwo(numbers))

Detect if number change from negative to positive or positive to negative

How to detect if positive or nagative changes ?
Example :
1 change to 2 = false
0 change to 1 = false
Because both are positive numbers
1 change to -1 = true
0 change to -1 = true
Because positive change to negative
-1 change to 0 = true
-1 change to 1 = true
Because negative change to positive
I do like..
var a_test,b_test;
if(a<0) {
a_test = 'negative';
} else {
a_test = 'positive';
}
if(b<0) {
b_test = 'negative';
} else {
b_test = 'positive';
}
if(a_test!==b_test) {
alert('Yeah!');
}
For test : http://jsfiddle.net/e9QPP/
Any better coding for do something like this ?
Wiki : A negative number is a real number that is less than zero
According to the Zen of Python,
Readability counts.
So, I present more readable and code-review passing version
if (a < 0 && b >= 0 || a >= 0 && b < 0) {
alert("Yeah");
}
You seem to want
if (a*b<0) alert('Yeah!');
If you want to consider 0 as a positive number, you may use
if (a*b<0 || (!(a*b) && a+b<0)) alert('Yeah!');
Taking a suitable sign function:
function sign(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
}
Then your problem can be expressed in clear and (hopefully) simple terms:
if (sign(a) !== sign(b)) {
// Your code here
}
Based on your criteria, it seems you simply want to compare the signs of the two numbers. The sign is stored in the highest bit of the number, therefore, to compare the signs, we can simply shift all the other bits off the number, and compare the signs.
Numbers in JavaScript are 64 bit (double), so we need to shift off the 63 bits preceding the sign:
if (a >>> 63 !== b >>> 63) alert('Yeah!');
Here is a jsFiddle demo
Here is a jsPerf comparison based on the 4 methods offered here.
Please note that this assumes that the numbers are 64 bit. I don't know if the spec restricts it to 64-bit, but it's plausible that there are browsers out there (or will be one day) where numbers are represented by perhaps a 128-bit number or greater.
Maybe a bit late, but I had the same problem.
Assuming you now that a and b are numbers why not:
if(a < 0 ? b >=0 : b < 0){
// your code here
}

Categories

Resources