The fastest way to create this number?

I am writing a function to expand a signed number to a wider bit length. This is a very commonly used action in the PowerPC command set. This is what I have so far:

function exts(value, from, to) { return (value | something_goes_here); } 

value is integer input, from is the number of bits that value uses, and to is the length of the target bit.

What is the most efficient way to create a number with to - from bits set to 1 , followed by from bits set to 0 ?

Ignoring the fact that JavaScript does not have the syntax of number 0b , for example, if I called

 exts(0b1010101010, 10, 14) 

I would like the OR function to have a value with 0b11110000000000 , returning a result with a character extension of 0b11111010101010 .

+6
source share
3 answers

A number containing p one bit followed by q zero bits can be generated via

 ((1<<p)-1)<<q 

this way in your case

 ((1<<(to-from))-1)<<from 

or much shorter

 (1<<to)-(1<<from) 
+5
source

I'm not too good at binary math in JavaScript ... But if you need an OR number with 0b11110000000000 , then I assume that you just convert it to decimal (which leads you to 15360 ), and do value | 15360 value | 15360 .

Relevant information that may be useful to you: parseInt("11110000000000", 2) converts a binary number (specified as a string) to a decimal number, and (15360).toString(2) converts a decimal number (15360 in this case) to a binary number ( the result is a string).


Revised decision

Probably a more elegant and mathematical method, but here's a quick and dirty solution:

 var S = ""; for(var i=0;i<p;i++) S += "1"; for(i=0;i<q;i++) S += "0"; S = parseInt(S, 2); // convert to decimal 
0
source

if you have a number 2 ^ q (= 1 shifted to the left by q), represented as an integer of width p + q bits, it has the representation:

 0...010...0 p-1 q 

then 2 ^ q - 1 has the representation

 0...01...1 pq 

which is exactly the opposite of you. So just flip the bits

therefore, you want NOT ((1 LEFT SHIFT by q) - 1) = ~((1 << q) - 1) in the notation

0
source

Source: https://habr.com/ru/post/888749/


All Articles