0

I'm using libraries with C interface in swift and in C error codes often are set with hexadecimal defines corresponded to signed integer values.

Is there any ways to set hexadecimal literal to signed integer type, for example:

var k: Int32 = 0x80000001

?

Paul Kamp
  • 101
  • 5
  • Is there an error with your code? Which one exactly? Your code is valid, except there is overflow. Your hex value is to big for being a Int32. If it was just `var k: Int32 = 0x0432; print("k: \(k)")` , output would be `k: 1074`. But if `k` is an Int64, output is `2147483649`, is that correct? – Larme Jul 05 '21 at 08:42
  • Does [this](https://stackoverflow.com/questions/31881274/unsigned-int-to-negative-int-in-swift) answer your question? – Sweeper Jul 05 '21 at 08:45

1 Answers1

2

There's a special initializer for just this case:

let x = Int32(bitPattern: 0x80000001)
print(x) // -2147483647
Gereon
  • 17,258
  • 4
  • 42
  • 73
  • thank you so much and shame on me ignoring apple documentation – Paul Kamp Jul 05 '21 at 09:13
  • Beware that defining an int via a binary bit pattern is platform-dependent. You will get different results on little-endian and big-endian hardware. – Duncan C Jul 05 '21 at 11:41