简体   繁体   中英

How to get Number of bits from Hex

For example how do I get 8 from 0x01, or 16 from 0x0001.

I want to know the number of bits a variable has.

var someNumber = 0x123456;
var len = whatToDoHere(someNumber);
console.log(len); // => 24 for example

Here are few alternatives:

 f1 = n => (Math.log2(n) & -8) + 8 // log2 (-Infinity & -8 = 0) f2 = n => ((n >>= 8) && f2(n)) + 8 // recursion f3 = n => n.toString(16).length + 1 << 2 & -8 // string length for (n of [0, 0xff, 0x100, 0xffff, 0x10000, 0xffffff]) console.log( f1(n) + '\\t' + f2(n) + '\\t' + f3(n) + '\\t0x' + n.toString(16) ) 

A number is just a number, it does not have any particular representation attached to it. Even if you say that it would be formatted in base16 (as hex) or base256 (bytes), that doesn't say anything about the number of leading zeroes (as in 0x01 vs 0x0001 ). If you know that however, you'd already know how many digits your formatted number has.

Another possible solution is to convert to a hex string and then measure the length of the string:

 const someNumber = 0x123456; const hexString = someNumber.toString( 16 ); const numberOfBits = hexString.length * 4; //each character is half a byte console.log( "Number of bits: ", numberOfBits ); 

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