To me your example appears somewhat confusing, int(bool(int())) is the fishiest part IMO. I assume bool(int()) is just (v^v1 != 0) in disguise and this is essentially
(v^v1 != 0) & (v^v2 != 0) & (v^v3 != 0) Am i right? Go can't & bools, so func bool2int(b bool) int { // This is what Go compiler can optimize well if b { return 1 } return 0 } And this leaves us with bool2int(v^v1 != 0) & bool2int(v^v2 != 0) & bool2int(v^v3 != 0) Is that correct? https://godbolt.org/z/jq368G I don't see branching in relevant parts. v == v1 || v == v2 will of course branch because || is a condition. Does that answer your question or maybe I am missing something? пт, 20 нояб. 2020 г. в 11:27, christoph...@gmail.com <christophe.mees...@gmail.com>: > > 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. -- 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/CAMteYTZDFWgzy6ONxRaUTLJrJo1H0dqeQiqx%2BeKdXcHdQoHEDA%40mail.gmail.com.