你将如何设置,并在围棋清除单个位? [英] How would you set and clear a single bit in Go?

查看:129
本文介绍了你将如何设置,并在围棋清除单个位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Golang,你如何设置和一个整数的明确各个位?例如,函数,这样的表现:

  clearBit(129,7)//返回1
 setBit(1,7)//返回129


解决方案

下面是设置位功能。首先,空间指定数目移位数1整数(因此它成为0010,0100等)。然后或将其与原始输入。这使得其它位不受影响,但将始终目标比特设置为1。

  //设置在整数n POS位。
FUNC setBit(N INT,UINT POS){INT
    N | =(1 <<;&下;正)
    返回否
}

下面是清除位的功能。第一移位数1的空格指定数目的整数(因此它成为0010,0100等)。然后翻转每个位掩码用 ^ 操作符(所以0010变成1101)。然后用按位与,它不触及数编为1,但将取消设置在其中设置为0掩码的值。

  //清除在n个POS机位。
FUNC clearBit(N INT,UINT POS){INT
    面膜:= ^(1 <<;&LT; POS)
    N'放大器; =面膜
    返回否
}

最后,这里有一个函数来检查了一下是否设置。移位数1的空格指定数目(因此它成为0010,0100等),然后与它的目标数量。如果所得到的数量是大于0(这将是1,2,4,8,等),然后该位被置

  FUNC hasBit(N INT,UINT POS){BOOL
    VAL:= N&安培; (1 <<;&下;正)
    返回(VAL大于0)
}

In Golang, how do you set and clear individual bits of an integer? For example, functions that behave like this:

 clearBit(129, 7) // returns 1
 setBit(1, 7)     // returns 129

解决方案

Here's a function to set a bit. First, shift the number 1 the specified number of spaces in the integer (so it becomes 0010, 0100, etc). Then OR it with the original input. This leaves the other bits unaffected but will always set the target bit to 1.

// Sets the bit at pos in the integer n.
func setBit(n int, pos uint) int {
    n |= (1 << pos)
    return n
}

Here's a function to clear a bit. First shift the number 1 the specified number of spaces in the integer (so it becomes 0010, 0100, etc). Then flip every bit in the mask with the ^ operator (so 0010 becomes 1101). Then use a bitwise AND, which doesn't touch the numbers AND'ed with 1, but which will unset the value in the mask which is set to 0.

// Clears the bit at pos in n.
func clearBit(n int, pos uint) int {
    mask := ^(1 << pos)
    n &= mask
    return n
}

Finally here's a function to check whether a bit is set. Shift the number 1 the specified number of spaces (so it becomes 0010, 0100, etc) and then AND it with the target number. If the resulting number is greater than 0 (it'll be 1, 2, 4, 8, etc) then the bit is set.

func hasBit(n int, pos uint) bool {
    val := n & (1 << pos)
    return (val > 0)
}

这篇关于你将如何设置,并在围棋清除单个位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆