简体   繁体   中英

How to convert a decimal (base 10) to 32-bit unsigned integer?

How to convert a decimal (base 10) to 32-bit unsigned integer?

Example:

If n = 9 (base 10), how to convert it to something like: 00000000000000000000000000001001 (base 2)?

Let's be clear that when you're talking about number bases, you're talking about textual representations (which code will see as strings). Numbers don't have number bases, they're just numbers (but more on this below) . A number base is a way of representing a number with a series of digits (text). So n = 9 isn't base 10 or base 36 or base 2, it's just a number. (The number literal is in base 10, but the resulting number has no concept of that.)

You have a couple of options:

Built in methods

The number type's toString accepts a radix (base) to use, valid values are 2 through 36. And the string padStart method lets you pad the start of a string so the string is the desired number of characters, specifying the padding character. So:

 const n = 9; const binaryText = n.toString(2).padStart(32, "0"); console.log(binaryText);

If your starting point is text (eg, "9" rather than 9 ), you'd parse that first. My answer here has a full rundown of your number parsing options, but for instance:

 const decimalText = "9"; const binaryText = (+decimalText).toString(2).padStart(32, "0"); console.log(binaryText);

Bit manipulation

"Numbers don't have number bases, they're just numbers" is true in the abstract, but at the bits-in-memory level, the bits are naturally assigned meaning. In fact, JavaScript's number type is an implementation of IEEE-754 double-precision binary floating point.

That wouldn't help us except that JavaScript's bitwise & and |operators are defined in terms of 32-bit binary integers (even though numbers aren't 32-bit binary integers, they're 64-bit floating point). that means we could also implement the above by testing bits using & :

 const n = 9; let binaryText = ""; for (let bit = 1; bit < 65536; bit *= 2) { binaryText = (n & bit? "1": "0") + binaryText; } console.log(binaryText);

// hoping u guys have already practiced javascript in leetcode using //andygala playlists

function flippingBits(n){ n = n.toString(2).padStart(32, "0");

n=(n.split(''))
for(let i=0;i<32;i++){ 
    (n[i]==='1')? n[i]='0': n[i]='1';
}
n=n.join('')
let n=parseInt(n,2)
return n;

} console.log(flippingBits(9))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM