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

MyMemoWiki

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

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

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

Excel VBA |

Shift_JISに変換

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

  1. Sub PrintByteTest()
  2. Dim s As String
  3. Dim b() As Byte
  4. s = "abcあいう"
  5. b = StrConv(s, vbFromUnicode)
  6. ' Shift_JIS
  7. GoSub print_byte
  8. Exit Sub
  9. print_byte:
  10. Dim i As Integer
  11. For i = 0 To UBound(b)
  12. Debug.Print Hex(b(i)) + " ";
  13. Next
  14. Return
  15. End Sub

結果

  1. call PrintByteTest
  2. 61 62 63 82 A0 82 A2 82 A4

Unicode(UTF-16LE)に変換

StringをそのままByteに代入

  1. Sub PrintByteTest()
  2. Dim s As String
  3. Dim b() As Byte
  4. s = "abcあいう"
  5. b = s
  6. ' Unicode (UTF-16LE)
  7. GoSub print_byte
  8. Exit Sub
  9. print_byte:
  10. Dim i As Integer
  11. For i = 0 To UBound(b)
  12. Debug.Print Hex(b(i)) + " ";
  13. Next
  14. Return
  15. End Sub
  16.  

結果

  1. call PrintByteTest
  2. 61 0 62 0 63 0 42 30 44 30 46 30

Javaと確認

Shift_JISとUTF-16LEに変換
  1. public class PrintByteTest {
  2. public static void main(String[] args) throws Exception {
  3. String s = "abcあいう";
  4. byte[] b = null;
  5. b = s.getBytes("Shift_JIS");
  6. for (int i=0; i<b.length; i++) {
  7. System.out.format("%X ", b[i]);
  8. }
  9. System.out.println("");
  10.  
  11. b = s.getBytes("UTF-16LE");
  12. for (int i=0; i<b.length; i++) {
  13. System.out.format("%X ", b[i]);
  14. }
  15. }
  16. }
結果
  1. >java PrintByteTest
  2. 61 62 63 82 A0 82 A2 82 A4
  3. 61 0 62 0 63 0 42 30 44 30 46 30