将字符串长度转换为二进制 [英] convert string lenght to binary
本文介绍了将字符串长度转换为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例输入:你好(最大长度7)
长度为5
样本输出:00 01 10 11 100
sample input: hello (max length 7)
length is 5
sample output: 00 01 10 11 100
推荐答案
System.Convert.ToString(hello.Length,2)
https://msdn.microsoft.com/en-us/library/14kwkz77(v = vs.110).aspx
System.Convert.ToString ("hello".Length , 2 )
https://msdn.microsoft.com/en-us/library/14kwkz77(v=vs.110).aspx
一种方法是:< a href =https://msdn.microsoft.com/en-us/library/14kwkz77%28v=vs.110%29.aspx> https://msdn.microsoft.com/en-us/library/14kwkz77 %28v = vs.110%29.aspx [ ^ ]。
获得字符串后,还需要插入空格分隔符,这将是一个简单的字符串操作。
你可以从头开始,以提高性能。然后,您需要在计算它们(0,1或空格)时逐个添加所有字符。要添加字符,请始终使用not string( immutable ),但System.Text.StringBuilder
。很明显,不可变类型的多个连接对性能来说真的很糟糕,因为连接会在每个操作上创建一个新的字符串实例,来回复制所有数据。
如何计算那些数字?您需要逐个提取所有位并添加0或1,具体取决于结果(并且,取决于位置,'')。现在,如何提取位?在循环中,首先创建一个位掩码。如果您的位位置index
,则位掩码为index<< 1
。如果给出整数值,其索引位于index
,则清除所有其他位。然后使用测试值(length
)和掩码执行按位OR运算。它会给你零值或不给你。如果为零,则添加0,如果非零,则添加1:if(length |(index<< 1)> 0)...
添加'1',否则添加'0'。在某些位置,还要在数字后添加''。
这就是全部。我希望你能用这个简单的描述完成代码。
-SA
One way is this: https://msdn.microsoft.com/en-us/library/14kwkz77%28v=vs.110%29.aspx[^].
After you get the string, you will also need to insert your blank space delimiters, which will be a simple string manipulations.
You can get it from scratch, to improve performance. Then you would need to add all characters one by one as you calculate them (0, 1 or blank space), all at once. For adding characters, always use not string (which is immutable), butSystem.Text.StringBuilder
. It is apparent that multiple concatenation on immutable type is really bad for performance, as concatenation creates a new string instance on every operation, copying all data back and forth.
How to calculate those digits? You need to extract all bits one by one and add 0 or 1, depending on result (and, depending on position, ' '). Now, how to extract bits? In a loop, first create a bit mask. If your bit position isindex
, the bit mask isindex << 1
. If gives you the integer value with the bit at indexindex
set, all other bits clear. Then perform bitwise OR operation with you test value (length
) and the mask. It will give you either zero value or not. If it is zero, add '0', if non-zero, add '1':if (length | (index << 1) > 0) …
add '1', otherwise add '0'. At certain positions, also add ' ' after the digit.
That's all. I hope you can complete the code using this simple description.
—SA
这篇关于将字符串长度转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文