Is there some process to convert a negative -4000 'Int' into a 'UInt8'?


Given this:

let negativeInt = -4000

is there some process to convert it into a UInt8


What UInt8 value do you want it to become?

You're probably looking for UInt8(truncatingIfNeeded: -4000), but the problem is unspecified as stated, since there's no "right answer" when converting -4000 to UInt8.


Thanks @scanon !


let n = UInt8(truncatingIfNeeded: -3000)

output: 72

// how to add a '0x' prefix?

// desired output: 0x72

I guess you want 0x48 in this case.

let value = 72
print(String(format: "0x%x", value)) // 0x48

Thanks. I would need a UInt8 value (not a String) as a result.

But the external representation of a UInt8 value has to be always in String form in some specified base (or radix). For example, 72 (decimal), and 0x48 (hex).

1 Like

This is my case, I need to convert myIntToUInt8Plus0x into a UInt8 value because then I must pass it to a Data type initializer.

let myInt = -3000 // Int (output: -3000)
let myIntToUInt8 = UInt8(truncatingIfNeeded: myInt) // UInt8 (output: 72)
let myIntToUInt8Plus0x = String(format: "0x%x", myIntToUInt8) // String (output: "0x48")
//let myDesiredUInt8 = UInt8(myIntToUInt8Plus0x) // UInt8 (desired output: 0x48)
//let myData = Data([myDesiredUInt8]) // Data

72 and 0x48 represent the exact same value when stored as a UInt8. The only difference is how you convert it to a string, not what the actual value is.


You don't need a myIntToUInt8Plus0x. UInt8 holds the same value. Like other people have said, the only difference is how you display it or reason about it. print(myUInt8) will display it as decimal not hex. 72 is the decimal representation of 0x48. That's why you were suggested to use String(format:), to visually format that byte as hexadecimal for output. For data transfer purposes a byte is a byte no matter how you choose to print it out.

So to transform an array of bytes to data you just need to initialise that Data with the array like so:

let myInt = -3000
let myByte = UInt8(truncatingIfNeeded: myInt)
let myData = Data([myByte])
1 Like

negativeInt [...] is there some process to convert it into a UInt8?

Since nobody stated it explicitly before:

UInt8 can't represent -4000 or any other negative value. UInt8 can represent values between zero and 255, nothing else.

If you "convert" any value outside of this range, i.e. by using UInt8(truncatingIfNeeded: -4000), you get a more or less random result. This result cannot be converted back to the original value.

Sorry, if that was clear before.


thanks for the explanation !

As much as it would be nice to think of things in this way, "%x" is just too archaic and I wouldn't touch it.