Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform bit shift without ("<<" || ">>") operator efficiently?

I am working on a OpenGL ES 2.0 shader and I have tightly packed data e.g. three 5-bit unsigned integers within a block of two bytes. To unpack this data I obviously need bit-shifting, but this is not supported in OpenGL ES Shading Language (see page 29 http://www.opengl.org/registry/doc/GLSLangSpec.Full.1.20.8.pdf)

Consequently I perform a number of *2 and /2 operations to emulate bit shifting.

Does anyone know a more efficient/elegant way to do this? Is there a trick I am not aware of?

Thanks!

like image 673
Lars Schneider Avatar asked Aug 12 '10 10:08

Lars Schneider


People also ask

How do you shift a bit correctly?

When shifting right with a logical right shift, the least-significant bit is lost and a 0 is inserted on the other end. For positive numbers, a single logical right shift divides a number by 2, throwing out any remainders.

Is bit shifting fast?

Bit-shifting is still faster, but for non-power-of-two mul/div by the time you do all your shifts and add the results it's slower again.

Which operators perform the shifting of bits from right to left or left to right?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.

What is the use of << shift operator?

The left shift operator ( << ) shifts the first operand the specified number of bits, modulo 32, to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.


3 Answers

If you are performing multiple shifts, you can use power operations. A bit shift is a multiplication or division by 2n, and a power operation would be more readable than multiple multiplication or division operations, I think, but I'm not sure about the performance. I suppose this is a more elegant solution, but probably not a more efficient one.

like image 53
Thomas Owens Avatar answered Oct 15 '22 17:10

Thomas Owens


Depending on what you are doing, these threads may be of some use:

GLSL: packing a normal in a single float link

Packing multiple floats into a single float value link

Packing floats to various bit depth targets (have to search the OpenGL.org forum as Stack overflow does not allow more than 2 links for new users)

like image 36
sqrtofnegone Avatar answered Oct 15 '22 18:10

sqrtofnegone


I've never used OpenGL, but the most efficient method would be a 16 bit lookup table for each type if your environment supports it. You would need to populate the table once on startup, but this should be very quick. You could use seperate tables for each type or a 2 dimensional table, eg, theTable[65536][3].

like image 24
jacknad Avatar answered Oct 15 '22 17:10

jacknad