简体   繁体   English

如何在iPhone应用程序中使用位类型?

[英]How can I use a bit type in my iPhone app?

I'm writing an iPhone app that's a mixture of Objective-C and C. I have 32-bit integer flags throughout my code that take on only two distinct values: 0 and 1. I'd like to use a data type that's smaller than 32 bits. 我正在编写一个混合了Objective-C和C的iPhone应用程序。我的代码中都有32位整数标志,这些标志仅采用两个不同的值:0和1。我想使用较小的数据类型超过32位。

Is there a type that's only one bit? 是否只有一种类型? What is the size of "BOOL" in Objective-C? Objective-C中“ BOOL”的大小是多少?

One solution I've considered is using one 32-bit integer for a group of 32 flags... then checking each flag in the following way: 我考虑过的一种解决方案是对一组32个标志使用一个32位整数...然后按以下方式检查每个标志:

if(ALL_FLAGS & (1 << SPECIFIC_FLAG)){...}

I'd really like to use just a "bit" type though. 我真的很想只使用“位”类型。

Cheers! 干杯!

The BOOL type under Objective C (actually it's a Cocoa definition, OBJC itself doesn't know the BOOL type) is using one byte. 目标C下的BOOL类型(实际上是可可定义,OBJC本身不知道BOOL类型)正在使用一个字节。 This is different from the Windows 32 BOOL which is equivalent to int or 32 bit. 这与Windows 32 BOOL(相当于int或32位)不同。

With smaller types you can use the typical C/C++ methods, either with bit shifts like in your example above or bit structures (in which case the compiler will do the bit shifting and testing). 对于较小的类型,您可以使用典型的C / C ++方法,例如上面示例中的位移或位结构(在这种情况下,编译器将进行位移和测试)。

typedef struct {
    unsigned someflag:1;
    unsigned anotherflag:1;
    unsigned yetnoather:1;
} MYFLAGS ;


MYFLAGS allflags;  

allflags.anotherflag= TRUE; 

if (allflags.anotherflag) { /* somecode */ }

还有一个CFBitVector,您可以在其中保存一组值...

Here are the definitions for the BOOL type, you could define your own type in the same way: 这是BOOL类型的定义,您可以用相同的方式定义自己的类型:

typedef signed char     BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#define OBJC_BOOL_DEFINED


#define YES             (BOOL)1
#define NO              (BOOL)0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM