# 常用位操作技巧（Golang）

seago123 · · 3234 次点击 · · 开始浏览

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

}

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

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

}