简体   繁体   English

Swift中的按位移位与Java不同

[英]Bitwise Shifting in Swift Different From Java

I am trying to shift RGB to a ColorInt like in Java. 我试图将RGB转换为Java中的ColorInt。

Java: The code below returns '-16777216' for a black color. Java:以下代码为黑色返回“ -16777216”。

int a = 255;
int r = 0;
int g = 0;
int b = 0;

int hcol = 0;
hcol |= (a & 0xFF) << 24;
hcol |= (r & 0xFF) << 16;
hcol |= (g & 0xFF) << 8;
hcol |= b & 0xFF;
System.out.println(hcol);

Swift: From what I know this should be the same exact code as the Java example. Swift:据我所知,这应该与Java示例完全相同的代码。 But it is returning only positive numbers and is '0' for black where '16777216'(not a negative) is white. 但是它只返回正数,黑色为“ 0”,而白色为“ 16777216”(不是负数)。

let a = 255
let r = 0;
let g = 0;
let b = 0;

var colInt = 0;
//colInt |= (a & 0xFF) << 24; (Adding this makes the variable even bigger)
colInt |= (r & 0xFF) << 16;
colInt |= (g & 0xFF) << 8;
colInt |= (b & 0xFF);

print("\(colInt)");

As you can see in the Swift example I don't have the alpha color. 如您在Swift示例中看到的,我没有alpha颜色。 If I add that it just makes the colInt an even higher number than the max amount of colors in the RGB spectrum. 如果我补充说,这只会使colInt的数字甚至高于RGB光谱中最大颜色的数量。

You are most likely running on a 64-bit machine so the swift Int type is actually 64-bit, while java int is always 32-bit. 您很可能在64位计算机上运行,​​因此Int类型实际上是64位,而java int始终是32位。 That "higher number" you see ( 4278190080 ) is actually 0x00000000FF000000 in 64-bit integer. 您看到的“更高的数字”( 4278190080 )实际上是64位整数中的0x00000000FF000000 Using Int32 should yield your expected result. 使用Int32应该会产生预期的结果。

let a : Int32 = 255
let r : Int32 = 0;
let g : Int32 = 0;
let b : Int32 = 0;

var colInt : Int32 = 0;
colInt |= (a & 0xFF) << 24;
colInt |= (r & 0xFF) << 16;
colInt |= (g & 0xFF) << 8;
colInt |= (b & 0xFF);

print("\(colInt)");    //-16777216

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

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