Go has a strict type separation between int and bool. For a normal usage 
this is OK. I guess it also ease assembly portability because there is not 
always a machine instruction to do so. 

For bit hacking, this is an unfortunate limitation. A handy feature of bool 
<-> int conversion is that true is converted to 1 and any integer different 
of zero to true. As a consequence, when we write int(bool(x)) we get 0 when 
x is 0, and 1 when x is not 0. I checked the math/bits package and there is 
not an equivalent function.

Is there a way around this that avoids the conditional branching ? 

The use case I have to test if an integer is in a quite small constant set 
of integers. With bool <-> int conversion, we can use binary operation like 
this for instance which would be valid in C

r := int(bool(v^v1))&int(bool(v^v2))&int(bool(v^v3))

This is to be compared with 

r := v==v1 || v==v2 || v==v3

The second form is of course more readable, but will also have a 
conditional branch at each ||. If most tested integers are different from 
v1, v2 and v3, the first form seam to me more efficient due to pipelining. 
Though branching prediction can mitigate the penalty. 

The best I could do as valid Go alternative is this

r := (v^v1)*(v^v2)*(v^v3)

but the multiplication is obviously not efficient. 

Did I miss something ? 

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/a2b743d7-011d-481f-9a0f-3f00f4507328n%40googlegroups.com.

Reply via email to