首先让我说在编程之前我从未真正使用过bit.我有一个可以处于3种状态的对象,我希望使用3位数组来表示这些状态.
例如:
我有一辆赛车,它可以前进,左,右站在一个站点上,比特将是000
如果汽车向前移动,如果向前,那么位将是010,如果向前,它将是110等...
我如何设置这些位,如何读取它们以获取值?
据我所知,C中最小的单位是a byte.这种约束来自哪里?中央处理器?
例如,如何将一个nibble或一个单独写入bit文件?
我正在寻找在任意位置提取任意长度(0 <=长度<= 16)的(无符号)位序列的最有效方法.骨架类显示了我当前的实现如何处理问题:
public abstract class BitArray {
byte[] bytes = new byte[2048];
int bitGet;
public BitArray() {
}
public void readNextBlock(int initialBitGet, int count) {
// substitute for reading from an input stream
for (int i=(initialBitGet>>3); i<=count; ++i) {
bytes[i] = (byte) i;
}
prepareBitGet(initialBitGet, count);
}
public abstract void prepareBitGet(int initialBitGet, int count);
public abstract int getBits(int count);
static class Version0 extends BitArray {
public void prepareBitGet(int initialBitGet, int count) {
bitGet = initialBitGet;
}
public int getBits(int …Run Code Online (Sandbox Code Playgroud) 好吧,听起来有点复杂,但这正是我想要做的:
10101010101{ 0, 2, 4, 6, 8, 10 }- 一个包含所有位置的数组这是我的代码:
UINT DQBitboard::firstBit(U64 bitboard)
{
static const int index64[64] = {
63, 0, 58, 1, 59, 47, 53, 2,
60, 39, 48, 27, 54, 33, 42, 3,
61, 51, 37, 40, 49, 18, 28, 20,
55, 30, 34, 11, 43, 14, 22, 4,
62, 57, 46, 52, 38, 26, 32, 41,
50, 36, 17, 19, 29, 10, 13, 21,
56, 45, 25, 31, 35, 16, 9, …Run Code Online (Sandbox Code Playgroud) 我将如何在C++中找到"零"位的数量.假设我有一个整数;
int value = 276;
Run Code Online (Sandbox Code Playgroud)
我有100010100位,但我如何计算零?
假设我需要编写C宏来返回存储无符号32位整数所需的位数(1..32).(结果等于上限(log2(n)).
我需要它作为编译时计算宏,而不是函数.
我可以
#define NBITS(n) ((n)&(1<<31)?32:(n)&(1<<30)?31:...
Run Code Online (Sandbox Code Playgroud)
它有效,但相当长.(速度与此无关,计算在编译时).
有没有更短的方法来编写这个宏?最短的?
如果具有偶数1位,则值具有偶数奇偶校验.如果具有奇数1位,则该值具有奇校验.例如,0110具有偶校验,并1110具有奇校验.
1如果x有平价,我必须返回.
int has_even_parity(unsigned int x) {
return
}
Run Code Online (Sandbox Code Playgroud) 我有一个类型的变量,sbyte并希望将内容复制到byte.转换不是值转换,而是每位复制.
例如,
如果mySbyte的位是:'10101100',转换后,相应的字节变量也将包含位'10101100'.
我正在尝试优化一些打包和解包例程.为了进行打包,我需要计算存储整数值所需的位数.这是当前的代码.
if (n == -1) return 32;
if (n == 0) return 1;
int r = 0;
while (n)
{
++r;
n >>= 1;
}
return r;
Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个函数来返回一个正整数的位数,小于(2 ^ 53)-1的Javascript限制.但是我被精确问题所困扰,并希望避免使用大整数库.
方法1:
function bitSize(num)
{
return Math.floor( Math.log(num) / Math.log(2) ) + 1;
}
Pass: bitSize( Math.pow(2, 16) -1 ) = 16
Pass: bitSize( Math.pow(2, 16) ) = 17
Fail (Should be 48): bitSize( Math.pow(2, 48) -1 ) = 49
Pass: bitSize( Math.pow(2, 48) ) = 49
Run Code Online (Sandbox Code Playgroud)
方法2:
function bitSize(num)
{
var count = 0;
while(num > 0)
{
num = num >> 1;
count++;
}
return count;
}
Pass: bitSize( Math.pow(2, 16) -1 ) = 16
Pass: …Run Code Online (Sandbox Code Playgroud)