Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert a long to int in Java vs. swift?

Tags:

java

swift

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?

like image 771
Bolo Avatar asked Sep 29 '15 15:09

Bolo


People also ask

How do you convert long to int in java?

There are basically three methods to convert long to int: By type-casting. Using toIntExact() method. Using intValue() method of the Long wrapper class.

Can you compare long to int?

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.


1 Answers

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 as Int32.

  • On a 64-bit platform, Int is the same size as Int64.

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, and long, 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.

like image 82
Sotirios Delimanolis Avatar answered Sep 20 '22 03:09

Sotirios Delimanolis