Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to create this number?

I'm writing a function to extend a number with sign to a wider bit length. This is a very frequently used action in the PowerPC instruction set. This is what I have so far:

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

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

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

Ignoring the fact that JavaScript has no 0b number syntax, for example, if I called

exts(0b1010101010, 10, 14)

I would want the function to OR the value with 0b11110000000000, returning a sign-extended result of 0b11111010101010.

like image 708
Delan Azabani Avatar asked May 22 '11 08:05

Delan Azabani


1 Answers

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

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

thus in your case

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

or much shorter

(1<<to)-(1<<from)
like image 57
Howard Avatar answered Oct 06 '22 04:10

Howard