Swift 中的 (0 << 12) 是什么意思?

What does (0 << 12) mean in Swift?

在文档中我发现一个枚举案例定义为:

kCGBitmapByteOrderDefault = (0 << 12)

据我所知,这意味着位移零 12 次...仍然是零。我错过了什么?

像这样的结构意味着占位符或不再支持的功能的文档。这意味着在求和中包含值 kCGBitmapByteOrderDefault 将产生相同的值;因此它仅用于文档。

如果查看所有相关值,您会看到:

kCGBitmapByteOrderMask     = kCGImageByteOrderMask,
kCGBitmapByteOrderDefault  = (0 << 12),
kCGBitmapByteOrder16Little = kCGImageByteOrder16Little,
kCGBitmapByteOrder32Little = kCGImageByteOrder32Little,
kCGBitmapByteOrder16Big    = kCGImageByteOrder16Big,
kCGBitmapByteOrder32Big    = kCGImageByteOrder32Big

kCGBitmapByteOrderMask0x7000(即移动超过12位后的三位;0b0111000000000000)。

所以 0 << 12 只是 "if the bits, after you shift over 12 bits, are 0" 的一种非常明确的表达方式。是的,0 << 12 实际上是 0,但当整个 CGBitmapInfo 值为零时,它明确表示 kCGBitmapByteOrderDefault 不是(因为可能还有其他有意义的非零值,前 12 位中的数据),但仅当前 12 位之后的位为零时。

所以,简而言之,<< 12 在技术上不是必需的,但可以使意图更加明确。

Apple Doc 对于 CGBitmapInfo:

The byte order constants specify the byte ordering of pixel formats.

...If the code is not written correctly, it’s possible to misread the data which leads to colors or alpha that appear wrong.

kCGBitmapByteOrder 的各种常量主要映射到 CGImageByteOrder 中类似命名的常量,后者没有 "Default."

详细找到这些值in the docs for CGImageByteOrderInfo

你问的是默认值,正如你所说的位移 0,它仍然是 0,但正如 Rob 所说,preceding/following 位仍然很重要。

您缺少的是其他选项:

kCGBitmapByteOrder16Little = (1 << 12) 16 位,小端格式。

kCGBitmapByteOrder32Little = (2 << 12) 32 位,小端格式。

kCGBitmapByteOrder16Big = (3 << 12) 16 位,大端格式。

kCGBitmapByteOrder32Big = (4 << 12) 32 位,大端格式。

这些使用不同的值,具体取决于 16 位与 32 位图像,以及您是否首先关心最低有效位或最高有效位。

"Default" (0 << 12) 遵循相同的 format/process 移位 12。并且,正如 Rob 指出的那样,前 12 位和任何后续位也有意义。使用这些其他选项对它们的解释方式与使用 "Default"

有不同的影响