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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With