This is a standard trick to find the least significant set bit in a word. Only 
works for 2's complement numbers!
    -x == ~x+1
For example: x = 00110000b (24), ~x+1 = 11001111+1 = 11010000. Adding them 
yields 00010000; thus only the least significant set bit remains set.

Note that func LSB(x uint64) uint64 { return x&-x } works too. In your example 
you get an error because in Go literal constants are untyped. It is a pragmatic 
decision -- see https://blog.golang.org/constants

> On Jul 23, 2017, at 5:50 AM, Pablo Rozas Larraondo 
> <p.rozas.larrao...@gmail.com> wrote:
> 
> I have seen Go code using this function to find out the least significant 
> byte of unsigned integers:
> 
> func LSB(ci uint64) uint64 { return uint64(ci) & -uint64(ci) }
> 
> This function works fine but I wonder why, if call the same AND operation, it 
> results in an error: "constant -X overflows uint64"
> 
> Here is a playground example to illustrate this:
> https://play.golang.org/p/_0EYtlLnmG
> 
> Does anyone know what changes when -uint64() is called in a return statement? 
> How a negative uint should be interpreted?
> 
> Thank you,
> Pablo
> -- 
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to