本文介绍了按位索引用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现数据的COM pression想法我已经过了,因为我想象它运行对一个大语料库的测试数据,我原以为到code在C(我主要是在脚本语言如Ruby和Tcl经验。)

I'm trying to implement a data compression idea I've had, and since I'm imagining running it against a large corpus of test data, I had thought to code it in C (I mostly have experience in scripting languages like Ruby and Tcl.)

看,我意识到,我不能简单地以指数作为我希望做按位比较简单的字符或INT类型变量的位,运营商。

Looking through the O'Reilly 'cow' books on C, I realize that I can't simply index the bits of a simple 'char' or 'int' type variable as I'd like to to do bitwise comparisons and operators.

我在这种看法正确吗?它是合理的,我用枚举类型重新presenting位(和使这些阵列,和写入功能转换和从CHAR)?如果是这样,就是这样一个类型和函数标准库定义已经地方?是否有其他(更好?)接近?有一些例如code的地方,有人可以点我?

Am I correct in this perception? Is it reasonable for me to use an enumerated type for representing a bit (and make an array of these, and writing functions to convert to and from char)? If so, is such a type and functions defined in a standard library already somewhere? Are there other (better?) approaches? Is there some example code somewhere that someone could point me to?

谢谢 -

推荐答案

这是什么凯尔说继,您可以使用宏来完成复杂的工作适合你。

Following on from what Kyle has said, you can use a macro to do the hard work for you.

这是可能的。

要设置的第n个位,使用或:

To set the nth bit, use OR:

X | =(1 <  权

x |= (1 << 5); // sets the 5th-from right

要清除位,使用和:

X - 放大器; =〜(1 <  第五,从右

x &= ~(1 << 5); // clears 5th-from-right

要翻转了一下,使用XOR:

To flip a bit, use XOR:

的x ^ =(1 <

x ^= (1 << 5); // flips 5th-from-right

或...

#define GetBit(var, bit) ((var & (1 << bit)) != 0) // Returns true / false if bit is set
#define SetBit(var, bit) (var |= (1 << bit))
#define FlipBit(var, bit) (var ^= (1 << bit))

然后你可以使用它在code,如:

Then you can use it in code like:

int myVar = 0;
SetBit(myVar, 5);
if (GetBit(myVar, 5))
{
  // Do something
}

这篇关于按位索引用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:45