Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

Dim b = Text.Encoding.GetEncoding("UTF-16LE").GetBytes(inputBox.Text)
Dim base64 = Convert.ToBase64String(b)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top