4

iOS装13-之bit

 3 years ago
source link: http://quangelab.com/bit-code/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

工作当中用到Go语言,看了看开源的http/request.go

发现如下代码

const (
	defaultMaxMemory = 32 << 20 // 32 MB
)

这个32M真是有逼格的写法,首先简单介绍一下«左移以为相当于乘以2,左移20相当于乘以2的20次幂

这个有个你需要装13的技能,就是背过常用的2的幂表

10 1024 1K

16 65536 64K

20 1048576 1MB

30 1073741824 1GB

40 1099511627776 1TB

最起码要知道1K 1M 1G 1T 各是2的多少次幂

位运算基础

按位& 与我们写判断条件的&&类似 都为true才为true,而这里是都为1才为1 按位| 与我们写判断条件的||类似 只要一个为true结果为true,而这里是只要一个为1结果为1 异或^ 不一样则为1,否则为0 取反~ 0变1,1变0 左移«  用来将一个数的各个二进制位全部左移若干位,所以相当于乘以2,但是左移比乘法快的多(参考C程序设计第三版 谭浩强 323页) 右移» 用来将一个数的各个二进制位全部右移若干位,无符号数左边高位补0,有符号数左边高位补0还是1取决计算机系统

位运算应用口诀

清零取数要用与,某位置一可用或 若要取反和交换,轻轻松松用异或

位运算应用

1、位掩码(BitMask)在iOS中用在NS_OPTIONS。 在UIView.h中可以看到有个@property(nonatomic) UIViewAutoresizing autoresizingMask; 而UIViewAutoresizing的定义如下

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
    UIViewAutoresizingFlexibleWidth        = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
    UIViewAutoresizingFlexibleHeight       = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};

再看上面UIViewAnimationTransition的定义

typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
    UIViewAnimationTransitionNone,
    UIViewAnimationTransitionFlipFromLeft,
    UIViewAnimationTransitionFlipFromRight,
    UIViewAnimationTransitionCurlUp,
    UIViewAnimationTransitionCurlDown,
};

前者是位掩码实现,可以自由组合,例如

autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin

代表右上自动调整边距。

取消顶部调整

autoresizingMask = autoresizingMask &~ UIViewAutoresizingFlexibleTopMargin

判断右边是否自动调整

if (autoresizingMask & UIViewAutoresizingFlexibleRightMargin) == UIViewAutoresizingFlexibleRightMargin

2、UI设计师给的颜色16进制例如0xff0000 如何得到10进制颜色

我们通常说的RGB颜色都是24位的,也就是R、G、B分别占8位。

#define mRGBToColor(rgb) [UIColor colorWithRed:((float)((rgb & 0xFF0000) >> 16))/255.0 green:((float)((rgb & 0xFF00) >> 8))/255.0 blue:((float)(rgb & 0xFF))/255.0 alpha:1.0]

(rgb & 0xFF0000) 可以取到红色其它置0 而右移16位因为一种颜色占8位,所以R要移动两个8位即16

3、判断奇偶 i & 1 == 1 奇数 i & 1 == 0 偶数


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK