無限不可能性ドライブ

『ニューラルネットワーク自作入門』に刺激されてExcelVBAでニューラルネットワークを作ってみたものの、やっぱり数学やらなきゃと思い少しずつやってきたのもあって、自分の知識の整理とかそういった感じです。

【VBA】文字列を2進数に変換してファイル保存する

f:id:celaeno42:20210312230450p:plain

Option Explicit

Public Sub 文字列を2進数に変換して保存()
    Dim filePath As String
    Dim fileNo As Long
    Dim txt As String
    
    txt = "userid" & vbCrLf & "password"
    txt = encode(txt)
    
    filePath = ThisWorkbook.Path & "\binary.dat"

    fileNo = FreeFile
    Open filePath For Output As #fileNo
        Print #fileNo, txt
    Close #fileNo
    
End Sub

'文字列を2進数に変換
Private Function encode(ByVal txt As String) As String
    Dim i As Long
    Dim ch As String
    Dim bin As String
    Dim frmt As String
    Dim res As String
    
    frmt = WorksheetFunction.Rept("0", 8)

    i = 1
    Do
        ch = Mid(txt, i, 1)
        '文字をアスキーコードに変換してから2進数(文字列)に変換
        bin = Format(WorksheetFunction.Dec2Bin(Asc(ch)), frmt)
        res = res & bin
        i = i + 1
    Loop Until i > Len(txt)
    
    encode = res
    
End Function