简体   繁体   English

如何使用Excel VBA将二进制字符串转换为整数位数组

[英]How to Convert Binary String into Array Of Integer Bit using Excel VBA

I'm having hardstop with this problem to solve in my Excel macro coding. 我在使用Excel宏编码解决此问题时遇到了困难。 My input data is a binary string '1110'. 我的输入数据是二进制字符串'1110'。 Need to extract the binary string and return each bit of binary in sequence into array (as integer bit). 需要提取二进制字符串并按顺序将二进制的每一位返回到数组中(作为整数位)。 Pls help me...really appreciate help for coaching. 请帮助我...非常感谢教练的帮助。

For each bit = 1, the array value for that bit = Power of 2. At the end, add up all the value. 对于每个位= 1,该位的数组值= 2的幂。最后,将所有值加起来。 Example: 例:

Input = 1110 (binary string) store into Array (i). 输入= 1110(二进制字符串)存储到数组(i)中。 i = 3 (total bit from input =4) i = 3(输入的总位= 4)

Array (0) = 1^2 to the pwr of 0 = 1
Array (1) = 1^2 to the pwr of 1 = 2
Array (2) = 1^2 to the pwr of 2 = 4
Array (3) = 1^2 to the pwr of 3 = 8

The final output to be returned is summation of all the array list.In this case, it'll be 15 返回的最终输出是所有数组列表的总和,在本例中为15

From the top of my head without testing this will get you close. 从我的头顶开始,无需测试,这将使您接近。

Dim bin as String

bin="1101"

Dim bits(Len(bin)) as Integer

Dim bitIndex as Integer

Dim sum as Integer
sum = 0
For bitIndex = 0 to Len(bin)-1
  bits(bitIndex) = CInt(Mid(bin,bitIndex+1, 1)) * (2 ^ bitIndex)
  Debug.Print bits(bitIndex)
  sum = sum + bits(bitIndex) 
Next

Debug.Print sum

您可以使用内置的Excel函数BIN2DEC(从分析工具库)获得最终答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM