画像ファイル
画像ファイル インデクサでbit処理(C#、VB.NET)
VB.NET コード
Option Strict On
Public Class Form1
'インデクサを持つクラス
Public Bit As indexbit = New indexbit()

'ビットの表示用のピクチャーボックスを作成
Public pb(15) As PictureBox
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
textBoxBit.Text = "0"
Bit.value = 0

'ピクチャーボックスの番号から配列番号を取得し
'そのピクチャーボックスをピクチャーボックスの
'配列に入れている
For Each cl As Control In groupBox1.Controls
'コントロールの名前にpictureBoxが付いていたら
If cl.Name.StartsWith("pictureBox") Then
'プログラムを読みやすくするだけpictureBoxの長さ
Dim subLength As Integer = "pictureBox".Length

'名前から番号を取得
Dim no As Integer = Int32.Parse(cl.Name.Substring(subLength, cl.Name.Length _
- subLength)) - 1

'ピクチャーボックスを配列に入れる
If (no < 17) Then
pb(no) = DirectCast(cl, PictureBox)
End If
End If
Next
End Sub
'ビット反転ボタン押下
Private Sub butBitSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butBitSet.Click
Try

'ビット番号を取得
Dim index As Integer = Int32.Parse(textBoxBit.Text)

'ビットの状態を反転させる
Bit(index) = Not Bit(index)

'反転結果を数値にして表示
textBoxInt.Text = Bit.value.ToString()
'ピクチャーボックスにビットを表示
setPicBoxColor()

Catch

MessageBox.Show("数値が設定されていません。")
End Try
End Sub
'ピクチャーボックスの表示を変える
Private Sub setPicBoxColor()
For i As Integer = 0 To 15
'インデクサが使用されている
If Bit(i) Then
pb(i).BackColor = Color.LightGreen
Else
pb(i).BackColor = Color.DarkGreen
End If
Next
End Sub
'数値をセットする
Private Sub butintSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butintSet.Click
'通常のプロパティにアクセス
Bit.value = UInt16.Parse(textBoxInt.Text)
'ピクチャーボックスの表示を変える
setPicBoxColor()
End Sub
End Class

'インデクサを持つクラス
Public Class indexbit

'フィールドで16ビットの値を保持
Private ibit As UInt16

'valueプロパティで数値の設定取得が出来る
Public Property value() As UInt16
Get
Return ibit
End Get
Set(ByVal value As UInt16)
ibit = value
End Set
End Property


'インデクサの記述
Default Property bit(ByVal index As Integer) As Boolean

'bitの取得
Get

'例外も投げることが出来る
'16ビット以上は例外を投げる
If index > 15 Then
Throw New System.Exception()
End If
'検査するビットの計算
Dim i As UInt16 = Convert.ToUInt16(Math.Pow(2, index))

'検査ビットが立っていたらtrueを返す
If (ibit And i) > 0 Then
Return True
Else
Return False
End If
End Get

'bitの設定
Set(ByVal value As Boolean)

If (index > 15) Then
Throw New System.Exception()
End If
'設定するビットの計算
Dim i As UInt16 = Convert.ToUInt16(Math.Pow(2, index))

'セットならビットのorを
If value = True Then
ibit = ibit Or i
'リセットはビットを反転させてandを取る
Else
ibit = ibit And Convert.ToUInt16((Not i))
End If

End Set
End Property
End Class
画像 上記C#コードのダウンロード
画像 上記VB2005のコードのダウンロード

画像ファイル