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!

4

2 回答 2

3

不幸的是,.NET 中的 UTF-16LE 简称为“Unicode”(代码页 ID 1200)。因此,用于 UTF-16LE 的正确编码对象是Encoding.Unicode. 第一步是获取字符串的 UTF-16LE 表示形式的字节数组,如下所示:

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

然后,您可以使用Convert该类将这些字节转换为 Base64 字符串,如下所示:

Dim base64 As String = Convert.ToBase64String(bytes)

该类Encoding具有几个最常见的编码对象(例如UnicodeUTF8UTF7)的公共属性。但是,如果将来您需要使用不太常见的编码对象,则可以使用该Encoding.GetEncoding方法获取它。该方法采用代码页 ID 或名称。支持的代码页列表可以在MSDN 的这个页面上的表格中找到。

于 2014-01-09T14:54:31.870 回答
1
Dim b = Text.Encoding.GetEncoding("UTF-16LE").GetBytes(inputBox.Text)
Dim base64 = Convert.ToBase64String(b)
于 2014-01-09T14:42:14.840 回答