Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

271
Views
is there a difference between these two snippets of code and if yes what is it?

function addBinary(a,b) {
  let sum= a+b 
  if (sum<0){
    sum=0xffffffff+sum+1
  }
 return parseInt(sum).toString(2)

}

and especially the logic of how 0xffffffff has been used to achieve same result

function decimalToBinary(decimal){
  return (decimal >>> 0).toString(2);
}

function addBinary(a,b) {
  return decimalToBinary(a+b);
}

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

The >>> operator always interprets the given number as an unsigned 32 bit number. When the second operand is 0, nothing changes to that and the result is unsigned.

So for instance, -1 in binary is 0xffffffff in signed 32-bit, where the most significant bit (at the left) is the sign bit. But because exceptionally the >>> does not interpret that as a sign bit, it actually is seen as a positive number, i.e. 0xffffffff. Compared to the original -1 that is 0x100000000 more! This is always the difference for negative inputs. For -2 you'll get 0xfffffffe, for -3 you'll get 0xfffffffd, ...etc.

The first function emulates this. If sum is negative, we must do something, as the other function (using >>>) will never return a negative number.

The idea is to add that 0x100000000 difference. In fact, the author of this function was prudent, and evidently didn't want to work with numbers that exceed the 32 bit range, so 0x100000000 was off the board (it uses 33 bits). But one can split the job into parts. We can add one less (0xffffffff) to the sum, and then add the remaining 1. This is just a theoretical game though. In JavaScript there is no problem in adding 0x100000000, so they could just as well have done that. In other languages however, those that use 32 bit numbers, it would be necessary to first add 0xffffffff and only then 1.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!