Delan Azabani
Delan Azabani

Reputation: 81384

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.

Upvotes: 6

Views: 168

Answers (3)

DavidJCobb
DavidJCobb

Reputation: 1131

I am not overly familiar with binary mathematics in JavaScript... But if you need to OR a number with 0b11110000000000, then I assume you would just convert that to decimal (which would get you 15360), and do value | 15360.

Relevant info that you may find useful: 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 solution

There's 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

Upvotes: 0

Bwmat
Bwmat

Reputation: 4578

if you have the number 2^q (= 1 shifted 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
  p    q

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

hence what you want is NOT((1 LEFT SHIFT by q) - 1) = ~((1 << q) - 1) in c notation

Upvotes: 0

Howard
Howard

Reputation: 39197

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)

Upvotes: 5

Related Questions