I have try to convert this code in Java to swift 2.0
long checksumValue = 4253726258L;
int liCrc32 = (int)checksumValue;
System.out.println("liCrc32" + liCrc32)
LiCrc32 is equal to -41241038
My swift version
let int64: Int64 = 4253726258
let a:Int = Int(int64)
a returns me 4253726258
What i don't understand why in Java the value is negative?
There are basically three methods to convert long to int: By type-casting. Using toIntExact() method. Using intValue() method of the Long wrapper class.
You can compare long and int directly however this is not recommended. Why is it not recommended? It is not better to cast long to integer before comparing, on the contrary, that can lead to overflow and thus to wrong results.
From the Swift documentation
Int
In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform’s native word size:
On a 32-bit platform,
Int
is the same size asInt32
.On a 64-bit platform,
Int
is the same size asInt64
.Unless you need to work with a specific size of integer, always use
Int
for integer values in your code. This aids code consistency and interoperability. Even on 32-bit platforms, Int can store any value between -2,147,483,648 and 2,147,483,647, and is large enough for many integer ranges.
Java's int
, on the other hand, is always 4 bytes.
The integral types are
byte
,short
,int
, andlong
, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, [...]
Casting from a long
to an int
causes a narrowing primitive conversion
A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With