位域、共用体常见示例

共用体的所有成员占用同一段内存,修改一个成员会影响其余所有成员。

共用体占用的内存等于最长的成员占用的内存

常用创建方式1
union Data{
int n;
char ch;
double f;
} a, b, c;

常用创建方式2
union Data{
int n;
char ch;
double f;
};
union data a, b, c;

定义一个Car类,有向前,向后,向左,向右四个属性

#import <Foundation/Foundation.h>
@interface Car : NSObject
@property (nonatomic, assign) BOOL front;
@property (nonatomic, assign) BOOL back;
@property (nonatomic, assign) BOOL left;
@property (nonatomic, assign) BOOL right;
@end

#import "Car.h"
//(1 << 2) 数字1(0b00000001)向左移2位,后面补0 (0b00000100)
//0b00000001
#define DirectionFrontMask    (1 << 0)
//0b00000010
#define LGDirectionBackMask     (1 << 1)
//0b00000100
#define DirectionLeftMask     (1 << 2)
//0b00001000
#define DirectionRightMask    (1 << 3)
@interface Car(){
    // 联合体
    union Direction{
        char bits;
        // 位域
        struct {
            char front  : 1;
            char back   : 1;
            char left   : 1;
            char right  : 1;
        };
    } _direction;
}

- (void)setFront:(BOOL)isFront {
    if (isFront) {
//常用赋值
//赋值bits,把DirectionFrontMask位,赋值为true
        _direction.bits |= DirectionFrontMask;
    } else {
//赋值bits,把DirectionFrontMask位,赋值为false
        _direction.bits &= ~DirectionFrontMask;
    }
    NSLog(@"%s",__func__);
}

- (BOOL)isFront{
    return (BOOL)_direction.front;
//    return !!_direction.front;
}
- (void)clearDirection{
_direction.front = 0;
//相当于 
//_direction.front = 0;
//_direction.back = 0;
//_direction.left = 0;
//_direction.right = 0;
}

@end
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iOS KunPeng

一天写不出一片好文章,感谢!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值