且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 ARGB 唯一地打包为一个整数?

更新时间:2023-01-31 22:31:38

您正在尝试进行基本转换或类似的操作.无论如何,逻辑就像在基本转换中一样.4 字节 = 32 位.所以 32 位无符号整数会很好.

You are trying to do a base convert or something of that sort. Anyway the logic is like in base converting. 4 bytes = 32 bit. So 32 bit unsigned integer would do well.

在这种情况下,您有:

ARGB = A<<24 + R<<16 + G<<8 + B

是这样的:
你有 4 个字节的数据,意思是

it's like this:
you have 4 bytes of data, meaning

xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx

其中 X 是 1 或 0 值位.你可以这样映射它们:

where X is either 1 or 0 valued bit. You map them like this:

AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB

然后你所要做的就是添加它们,但在此之前你需要移动位.您将 A 位向左移动 8*3(超出 RGB 位),然后将 R 位移动 8*2,依此类推.

and then all you have to do is to add them, but before that you shift the bits. You shift the A bits to the left, by 8*3 (to be beyond the limits of R, G and B bits), then shift the R bits by 8*2, and so on.

您最终将这些 32 位整数相加:

You end up adding these 32 bit integers:

AAAAAAAA 00000000 00000000 00000000
00000000 RRRRRRRR 00000000 00000000
00000000 00000000 GGGGGGGG 00000000
00000000 00000000 00000000 BBBBBBBB

其中 ARGB 可以是 01,作为一个整体表示通道的8位值.然后您只需将它们相加,即可获得结果.或者如 DarkDust 所写,不要使用 + 运算符,而是使用 |(按位或)运算符,因为在这种特殊情况下它应该更快.

Where A, R, G, B can be either 0 or 1, and represent as a whole, the 8 bit value of the channel. Then you simply add them, and obtain the result. Or as DarkDust wrote, use not the + operator, but instead the | (bitwise or) operator, since it should be faster in this particular case.