0
0

More than 1 year has passed since last update.

長整数型で表せる10進数を4Byte(32bit)の2進数の文字列型に変換するVBAコード

Last updated at Posted at 2022-07-24
'↓*******************************************************************************↓
'+-------------------------------------------------------------------------------+
'|  正負の整数の10進数(整数型)を4Byteの2進数(文字列型)に変換
'|
'|  引数 decimalNumber: 10進数(長整数型(long))-2,147,483,648~2,147,483,647の整数
'|  返値 Dec2Bin:        2進数(文字列型(string))
'+-------------------------------------------------------------------------------+
Public Function Dec2Bin(ByVal decimalNumber As Long) As String
    Dim cnt As Byte                                 '繰り返し処理用
    Dim blnNeg As Boolean: blnNeg = False           '負値フラグ
    Dim precisionByte as Byte: precisionByte = 4    '精度(Byte数)
    Dim precisionBit As Byte                        '精度(ビット数)
    Dim strTmp As String: strTmp = ""               '途中計算用

    '精度(bit数)を求める
    precisionBit = precisionByte * 8

    '負値の場合
    If decimalNumber < 0 Then
        '後続処理用の負値フラグ
        blnNeg = True
        '10進数で-2147483648の絶対値を取るとオーバーフローするので例外処理
        If decimalNumber = -2147483648# Then
            Dec2Bin = "10000000000000000000000000000000"
            Exit Function
        End If
        '絶対値を取って正の値にする
        decimalNumber = Abs(decimalNumber)
    End If

    '精度(bit数)-1桁の2進数で数値を表記する
    For cnt = 0 To precisionBit - 2
        If (decimalNumber And 2 ^ cnt) <> 0 Then
            Dec2Bin = "1" & Dec2Bin
        Else
            Dec2Bin = "0" & Dec2Bin
        End If
    Next cnt

    '一番上の桁に0を付与して桁数を精度(bit数)にする
    Dec2Bin = "0" & Dec2Bin

    '負値の場合
    If blnNeg Then
        '0と1を反転(「1の補数」を作る)
        Dec2Bin = Replace(Dec2Bin, "0", "a") 'aは仮置き。1以外なら何でもよい
        Dec2Bin = Replace(Dec2Bin, "1", "0")
        Dec2Bin = Replace(Dec2Bin, "a", "1")

        '更に2進数で1を加える(「2の補数」を作る)
        For cnt = 1 To precisionBit
            If Left(Right(Dec2Bin, cnt), 1) = "1" Then
                strTmp = "0" + strTmp
            Else
                Dec2Bin = Left(Dec2Bin, precisionBit - cnt) + "1" + strTmp
                Exit For
            End If
        Next cnt
    End If

End Function
'↑*******************************************************************************↑
0
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
0
0