Peter_Z
1
Hi,
I need to multiply an 8 bit UNSIGNED number with an 8 bit SIGNED number and get the result as a 16bit SIGNED number. ie Int16 = UInt8 x Int8.
In other cases where I need to multiply UInt8 x UInt8 and Int8 x Int8 and get the resulting 16 bit number, I have been using the multipliedFullWidth functions, however I am not sure how to handle this particular situation. Can anyone advise me on the correct way to do this in Swift?
Thanks!
scanon
(Steve Canon)
2
func multiply(_ a: UInt8, _ b: Int8) -> Int16 {
// Don't need to worry about overflow, because a and b are both
// representable as Int16 and the result is in the range
// -0x7f80...0x7e81 (-128*255 ... 127*255).
Int16(a) &* Int16(b)
}
1 Like
jrose
(Jordan Rose)
3
Bonus: don't worry about not worrying about overflow, the compiler can do it for you here.
5 Likes
scanon
(Steve Canon)
4
To be clear, my use of &* is intended to inform the reader that the code cannot trap, not the compiler =)
Peter_Z
5
Thanks to both of you - much appreciated.