VB.NET 字符串转二进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25404993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:04:10  来源:igfitidea点击:

Convert from string to binary in VB.NET

vb.netstringbinarytype-conversion

提问by baraa

Let's say that I have the string "A3C0", and I want to store the binary value of it in a Boolean array.

假设我有一个字符串“A3C0”,我想将它的二进制值存储在一个布尔数组中。

After the conversion (from string to binary) the result should be = 1010001111000000

转换后(从字符串到二进制)结果应该是 = 1010001111000000

Then I want to store it in this array,

然后我想把它存储在这个数组中,

dim bits_array(15) as Boolean

at the end:

在末尾:

bits_array(0)=0
bits_array(1)=0
 .
 .
 .
 .
bits_array(15)=1

How can I do this?

我怎样才能做到这一点?

采纳答案by Pradeep Kumar

It's easy.

这很简单。

Function HexStringToBinary(ByVal hexString As String) As String
    Dim num As Integer = Integer.Parse(hexString, NumberStyles.HexNumber)
    Return Convert.ToString(num, 2)
End Function

Sample Usage:

示例用法:

Dim hexString As String = "A3C0"
Dim binaryString As String = HexStringToBinary(hexString)
MessageBox.Show("Hex: " & hexString & "    Binary: " & binaryString)

To get the binary digits into an array, you can simply do:

要将二进制数字放入数组,您只需执行以下操作:

Dim binaryDigits = HexStringToBinary(hexString).ToCharArray

回答by Pradeep Kumar

Let sbe the input string with value A3C0, outputbe a variable to store the output. loop will iterate each letter in the input and store it in the temporary variable temp. Now see the code:

s与值的输入串A3C0output是存储输出的变量。循环将迭代输入中的每个字母并将其存储在临时变量中temp。现在看代码:

Dim s As String = "A3C0"
Dim output As String = ""
Dim temp As String = ""
For i As Integer = 1 To Len(s)
    temp = Mid(s, i, 1)
    output = output & System.Convert.ToString(Asc(temp), 2).PadLeft(4, "0")
    ' converting each letter into corresponding binary value
    'concatenate it with the output to get the final output 
Next
MsgBox(output)' display the binary equivalent of the input `s` 
Dim array() As Char = output.ToArray()' convert the binary string  to binary array

Hope that this is actually you are expected.

希望这实际上是您所期望的。