리루

Convert string to Unicode 본문

# Study/VBA

Convert string to Unicode

뚱보리루 2016. 12. 27. 09:41

문자열을 Unicode로 변환한다.

 

아래에 구현된 코드는 2byte가 넘는 문자열의 경우에는 Little endian 형태가 적용되고(ex. 이 -> C7 74(big) -> 74 C7(little) ),

 

2byte가 넘지 않는 문자열의 경우에는 그대로 Big endian으로 사용된다(ex. a -> 61 -> 61 00)

 

왜 위에서 2byte가 넘지 않을 경우에 "00 61"이 아니라 "61 00"으로 되는지는 공부가 필요한 부분이다.

 

 

'------------------------------------------------------------------------------------------------------------------------------------------------------

Function StringToUnicode(str As String)

    Dim i As Integer
    Dim strLen As Integer
    strLen = Len(str)

 

    'Seperate character by character
    For i = 1 To strLen

        StringToUnicode = StringToUnicode & " " & CharToUnicode(Mid(str, i, 1))

    Next i

 

End Function

 

'------------------------------------------------------------------------------------------------------------------------------------------------------

 

-'-----------------------------------------------------------------------------------------------------------------------------------------------------

Function CharToUnicode(ch As String)

 

    Dim charCode As Long
    Dim bigEnd As String
   
    charCode = AscW(ch)

    If charCode < 0 Then

        charCode = charCode + 65536

    End If

 

    bigEnd = Hex(charCode)


    'When 2bytes unicode, change to little endian
    If Len(bigEnd) > 2 Then
   
        CharToUnicode = Right(bigEnd, 2) & " " & Left(bigEnd, 2)
       
    Else
   
        CharToUnicode = bigEnd & " 00"
       
    End If
   

End Function
'------------------------------------------------------------------------------------------------------------------------------------------------------