gpt4 book ai didi

java - 如何在 Java 中逐位读取整数?

转载 作者:IT老高 更新时间:2023-10-28 21:07:04 28 4
gpt4 key购买 nike

我想将 int 作为输入,并返回第 k 位。

int getBit(int n, int k){
return kth bit in n;
}

我该怎么做?

最佳答案

使用位运算符:

int getBit(int n, int k) {
return (n >> k) & 1;
}

解释(位):

n
100010101011101010 (example)
n >> 5
000001000101010111 (all bits are moved over 5 spots, therefore
& the bit you want is at the end)
000000000000000001 (0 means it will always be 0,
= 1 means that it will keep the old value)
1

关于java - 如何在 Java 中逐位读取整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14145733/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com