How to correctly multiply UInt8 x Int8 and get a 16 bit result

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!

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

Bonus: don't worry about not worrying about overflow, the compiler can do it for you here.

5 Likes

To be clear, my use of &* is intended to inform the reader that the code cannot trap, not the compiler =)

Thanks to both of you - much appreciated.