lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Mar 26, 2014 at 12:41 PM, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
Just for curiosity, do you remember those techniques?

One application that comes to my mind is extracting a signed M bit field from bit position P in a word of length N:

(x << (N - (P + M))) >> (N - M)

where >> is signed (otherwise the field won't be sign extended), and bit positions are little endian, M <= N, P <= N.

This sort of thing comes up in embedded applications, e.g., pulling a ADC value out of a SPI packet, or parsing a binary comm buffer.

This is a case where // 2^(N - M) would be fine... assuming the // and ^ operators are performant enough, which I am skeptical about in embedded processors where integer mode would be used. In these cases I would resort to the technique in my Plea, which is a bit more complicated:

return (((x << (N - (P + M))) >> (N - M)) ~ (1 << (M - 1))) - (1 << (M - 1))

In many applications, though, the parameters M, P, and N are known at design time, so most of these operations can be eliminated.

e