常用位操作技巧(Golang)
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 + 1 return
}
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
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。