adrianmcmenamin adrianmcmenamin - 26 days ago 10
Groovy Question

Sign extending from a fixed bit width in Java/Groovy

I want to sign extend 12 bit numbers to 32 bits in Groovy (or Java, of course). I can find various recipes for this in C/C++ and so on, but not for Groovy/Java - could someone give me an algorithm or a code fragment?

Answer

With thanks to @harold:

 (x << 20) >> 20 or (x ^ 0x800) - 0x800, whichever you like best/is more   convenient. The first is easier to understand but it rarely gives further possibilities for simplification
Comments