1
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?

More than 5 years have passed since last update.

[メモ]VB.NETでのビット演算について 2017.11.15修正

Last updated at Posted at 2017-11-12

状況

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

1
0
0

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
1
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?