0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swiftでunsigned shortからshortへ変換する

Last updated at Posted at 2024-05-25

組込み機器から送られてくるデータ、例えばBluetoothやUSBなどで通信するような場合です。

shortunsigned shortが16bitのシステムでの例です。

通信で数値が送られてくる場合、それが(signed)shortなのか、unsigned shortなのかはわかりません。

送られてくる数値が0x7fffまでならいいですが、0x8000からが危険です。

Swiftに用意されている16bit値を扱うInt16は、文字どおり符号付きの数値を扱うため、例えば組込み機器から受け取った0xffffをそのままInt16(0xffff)としてオブジェクトを作るとエラーになります。
Swiftでの整数0xffff0x0000_0000_0000_ffffと同意で、10進数で65,535です。符号付き16bitの最大値である32,767を超えています。
だけど、0xffffは-1として扱って欲しい...

その時は、こうやって初期化します。

Int16(truncatingIfNeeded: 0xffff)

これでオブジェクトの値は-1になります。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?