這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
1,判斷奇偶
for i := 0; i < 100; i++ { if i % 2 == 0 { println(i) } if i & 0x1 == 0 { println(i) }}
2,交換兩個數
func Swap(a, b *int) {if *a^*b != 0 {temp := *a*a = *b*b = temp}}func Swap(a, b *int) {if *a^*b != 0 {*a = *a + *b*b = *a - *b*a = *a - *b}}func Swap(a, b *int) {if *a^*b != 0 {*a ^= *b*b ^= *a*a ^= *b}}
3,交換符號
func ExcangeSymbol(a int) (ret int) {ret = ^a + 1return}
4,求絕對值
func CalcAbs(a int) (ret int) { ret = (a ^ a>>31) - a>>31 return}
5,二進位逆序
func ByteReverse(a int) int { a = ((a & 0xAAAA) >> 1) | ((a & 0x5555) << 1) a = ((a & 0xCCCC) >> 2) | ((a & 0x3333) << 2) a = ((a & 0xF0F0) >> 4) | ((a & 0x0F0F) << 4) a = ((a & 0xFF00) >> 8) | ((a & 0x00FF) << 8) return a}
6,求1的個數
func CalcOneNum(a int) int { a = ((a & 0xAAAA) >> 1) + (a & 0x5555) a = ((a & 0xCCCC) >> 2) + (a & 0x3333) a = ((a & 0xF0F0) >> 4) + (a & 0x0F0F) a = ((a & 0xFF00) >> 8) + (a & 0x00FF) return a}