如何使用按位运算符提取整数中的数字
如何使用按位运算符从整数中提取数字。即我想提取整数 n=123456 中的 234 我知道可以使用 and、or、xor 按位运算符,但我不确定如何?谢谢
How do I extract digits from an integer using bitwise operator. i.e. I want to extract 234 in the integer n=123456 I know this is possible using and, or, xor bitwise operator but I'm not sure How? thnx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您此时不想按位,我相信您可以像这样提取单个数字:
我不确定这是否是最快/最有效的方法,但它有效。
将数字拼接起来也应该很容易,只需乘以 10 的递增幂即可。
如果有人有更好的解决方案,请告诉。
If you don't want bitwise at this point, I believe you can extract individual digits like this:
I'm not sure if this is the fastest/most-efficient way, but it works.
Stitching the digits back together should be easy as well, just multiply by increasing powers of ten.
If anyone has a better solution, please tell.
由于这被标记为家庭作业,我只会解释基本概念,实际上我不会给出答案。
您可以使用按位运算来提取以 2 为基数的数字的各个位。因此,如果您的号码是 10110101,并且您想在末尾获得 0101,则必须设置一个掩码,然后进行二进制与运算以过滤掉不重要的数字。你的掩码应该类似于 00001111。当你和他们在一起时,只留下你想要的数字。
10110101& 00001111==00000101
Since this is tagged as homework, i'm only going to explain basic concepts, I'm not actually going to produce an answer.
You use bitwise operations to extract individual bits of a base 2 number. So if your number is 10110101, and you want to get the 0101 at the end, you would have to set up a mask, and then do a binary anding to filter out the unimportant digits. Your mask should look something like 00001111. When you and them together, only the digits you want are remaining.
10110101 & 00001111 == 00000101
您可以使用 长除法一一提取数字。您将需要实现进行长除法所需的原语。
具体如何操作取决于您被允许使用的精确操作集。例如,如果不允许添加,则必须构建自己的添加操作。如果不允许进行减法,则需要使用异或、增量和加法来构建减法。
一旦有了除法原语,一切就很容易了。连续除以 1010b 将提取数字。
You can extract the digits one by one using long division. You will need to implement the primitives you'll need to do long division.
Exactly how you do it depends on the precise set of operations you're allowed to use. For example, if you're not allowed to add, you'll have to build your own add operation. If you're not allowed to subtract, you'll need to build a subtract with XOR, increment, and add.
Once you have a division primitive, it's easy. Successive divisions by 1010b will extract the digits.
将 int 转换为二进制。将所需位置的数字移动到最左边或最右边。根据我们执行的移位,按位与,数字全为 0,最左边或最右边只有一个 1。将二进制重新转换回十进制。
也许看看这个可能会有所帮助:使用按位运算符提取位
Convert the int to binary. Move the digit at position you need to the leftmost or rightmost. Bitwise AND with number having all zeros and just one 1 at the leftmost or rightmost according to the shifting we have performed. re covert the binary back to decimal.
Maybe taking a look at this might help: Extracting bits with bitwise operators