Reputation: 531
Wondering what the ideal way is of converting a group of smaller bits into larger bits. For example, these specific cases:
Wondering what the generic technique is so I can apply it to any number. If it only works for multiples of 8 then that's fine, but ideally it would be able to handle these cases as well.
I was thinking you just add them but it sounds like there is a technique for shifting them which I'm not sure exactly how it works generically.
Upvotes: 3
Views: 1720
Reputation: 2169
I assume that by "convert" you mean to "concatenate" the bits.
Here's how you would do that with shift:
var int1 = 23; // "8 bit" number, stored in integer variable
var int2 = 67; // another one
var int3 = 189; // a third
var concatInt = ( int1 << 16 ) + ( int2 << 8 ) + int3;
Here, the value of "concatInt" is the bitwise concatenation of the 3 numbers [int1][int2][int3]
Of course, you can do this with any numbers and any bits, as long as you fit within a 32 bit integer.
Here is some more reading on that: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
Upvotes: 2