| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Excel VBA 文字列をバイト配列に変換

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

文字列をバイト配列に変換

Excel VBA |

Shift_JISに変換

StringをByteに代入時にstrConvで、Shift_JISに変換

Sub PrintByteTest()
    Dim s   As String
    Dim b() As Byte
    
    s = "abcあいう"
    b = StrConv(s, vbFromUnicode)
        
    ' Shift_JIS
    GoSub print_byte
    
    Exit Sub
    
print_byte:
    Dim i As Integer
    
    For i = 0 To UBound(b)
        Debug.Print Hex(b(i)) + " ";
    Next
    Return
End Sub

結果

call PrintByteTest
61 62 63 82 A0 82 A2 82 A4 

Unicode(UTF-16LE)に変換

StringをそのままByteに代入

Sub PrintByteTest()
    Dim s   As String
    Dim b() As Byte
    
    s = "abcあいう"
    b = s
    
    ' Unicode (UTF-16LE)
    GoSub print_byte
    
    Exit Sub
    
print_byte:
    Dim i As Integer
    
    For i = 0 To UBound(b)
        Debug.Print Hex(b(i)) + " ";
    Next
    Return
End Sub

結果

call PrintByteTest
61 0 62 0 63 0 42 30 44 30 46 30 

Javaと確認

Shift_JISとUTF-16LEに変換
public class PrintByteTest {
    public static void main(String[] args) throws Exception {
        String s = "abcあいう";
        byte[] b = null;
        
        b = s.getBytes("Shift_JIS");
        for (int i=0; i<b.length; i++) {
            System.out.format("%X ", b[i]);
        }
        System.out.println("");

        b = s.getBytes("UTF-16LE");
        for (int i=0; i<b.length; i++) {
            System.out.format("%X ", b[i]);
        }
    }
}
結果
>java PrintByteTest
61 62 63 82 A0 82 A2 82 A4
61 0 62 0 63 0 42 30 44 30 46 30