-2

I have to port the following Java code in Swift.

// Java code
byte [] nodeId = [47, -29, 4, -121]
int numNodeID = 0;
for(int i=0; i < 4; i++){
   numNodeID |= ((nodeId[i]&0x000000FFL) << (i*8));
}

I wrote

// Swift code
var nodeId: [Int8] = [47, -29, 4, -121]
var numNodeId: Int = 0
for index in 0..<4 {
    numNodeId |= ((Int(nodeId[index]) & 255) << (index*8))
}

The results are different. In Java I obtain the int -2029722833, in swift the int 2265244463. The java result is the signed 2's complement of the swift one.

How can I obtain the signed integer (-2029722833) also in swift?

Giorgio
  • 1,973
  • 4
  • 36
  • 51
  • 2
    Java ints are signed 32-bit integers. Use `Int32` in Swift to get the same result. – Martin R Apr 04 '22 at 09:54
  • 2
    You seem to just want to convert 4 bytes into a `Int32`. There are [much better ways](https://stackoverflow.com/q/32769929/5133585) to do that. – Sweeper Apr 04 '22 at 09:56

1 Answers1

1

You're currently thinking that int translates to Int. But no!

On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.

I can't tell what your code is actually doing, but a direct translation requires Int32 .