状況
PLCからShort型のデータ(-32768~32767)を取り出し、それに対してビット演算を行う。
困ったこと
取得データがSignedShortのため、ビット演算時に取得データをUnsigned型に変換しないといけない。
(というか、簡潔な方法がこれしか浮かばなかった。)
解決
以下が、使用した関数。
2017.11.15修正
Public Function GetBitRange(ByVal data As Short, ByVal pos As Integer) As Integer
Dim range As UShort = 2 ^ pos
Return (ToUnsigned(data) And range) \ range
End Function
Public Function GetBitRange(ByVal data As Short, ByVal startpos As Integer, ByVal endpos As Integer) As Short
If startpos = 0 AndAlso endpos = 15 Then
Return data
End If
Dim range As UShort = 0
For i As Integer = startpos To endpos
range += 2 ^ i
Next
Return (ToUnsigned(data) And range) \ 2 ^ startpos
End Function
Public Function ToUnsigned(ByVal data As Short) As UShort
If data < 0 Then
Return data + UShort.MaxValue + 1
Else
Return data
End If
End Function
使用方法
dataはPLCから取得したデータ
pos,startpos,endposはビット番号(0-15)
startposとendposの大小が逆だったら動作しないのは(まだ)仕様です。
便利コードをまとめてるので、バグとかあったら教えてください。
https://github.com/keuxkeu/useful-codes-for-vb.net