2

I'm throwing together a program as a refresher for VB.net, and I figured I might as well make it do something that I have to do a lot anyways: Convert an input string into UTF-16LE and then into Base64.

Now, in PHP, I can do it like this:

<?php
$UTF8_String = "example string"; 
$UTF16_String = mb_convert_encoding($UTF8_String,"UTF-16LE","UTF-8");
$base64_encoded = base64_encode($UTF16_String);
echo $base64_encoded;

Sweet and simple.

...but in vb.net, I can't figure out how to get the string from

Dim strInput = inputBox.Text

convert it to UTF-16LE (it has to be UTF-16LE), and then the convert the resulting string to Base64.

Thank you!

Edit: Gserg and Steven's code both works equally well, and it helps to seeing two methods of converting text: One with specifiable encoding and one with Unicode. Steven's answer is more complete at this time, so I'll accept it. Thank you!

Austin Burk
  • 930
  • 4
  • 15
  • 33

2 Answers2

3

UTF-16LE in .NET, unfortunately, is simply called "Unicode" (code page ID 1200). So, the proper encoding object to use for UTF-16LE is Encoding.Unicode. The first step is to get a byte array for the UTF-16LE representation of the string, like this:

Dim bytes() As Byte = Encoding.Unicode.GetBytes(inputBox.Text)

Then, you can convert those bytes into a Base64 string by using the Convert class, like this:

Dim base64 As String = Convert.ToBase64String(bytes)

The Encoding class has public properties for several of the most common encoding objects (e.g. Unicode, UTF8, UTF7). If, in the future, however, you need to use a less common encoding object, you can get it by using the Encoding.GetEncoding method. That method takes either a code page ID or name. The list of supported code pages can be found in the table on this page of the MSDN.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
1
Dim b = Text.Encoding.GetEncoding("UTF-16LE").GetBytes(inputBox.Text)
Dim base64 = Convert.ToBase64String(b)
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • Thank you so much! I did have to include the `System.Text` part for the first line, for some reason the `Imports System.Text` doesn't work. In other words, you just made my day nicer. Thank you! – Austin Burk Jan 09 '14 at 14:47