如何将字符串转换为二进制数 [英] How do I can convert string to binary number

查看:144
本文介绍了如何将字符串转换为二进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我需要有关如何将字符串转换为二进制数的帮助。 *但是具体的条件是这个二进制数需要怎么样。



我得到的字符串总是由'0'和'1'组成,就像这样'0','000','001,'010','101','00','10'(其中一个,不是全部)......



所以我需要将其转换为二进制,但是相同数量的0和1就像字符串一样。



这个问题的第二部分是:我如何可以添加一个,到那个二进制数,然后得到这样的东西,

000 + 1 = 001,

001 + 1 = 010,

010 + 1 = 011,

011 + 1 = 100或

00 + 1 = 01,

01 + 1 = 10。 ..



顺便说一句。这是一个WinForm(VisaulStudio),而不是一个控制台程序。



提前致谢。



*问题更新,现在更确切地说是我要问的问题。

*你可以在下面的评论中找到更清楚的有关问题的信息。





所以,首先,输入信息,让我们采取类似的东西(有完整的代码,所以你可以理解我在说什么。

http://pastebin.com/mCb99yC7 [ ^ ])



120.70.144.0/22

5



我们有(broj1 = 120,broj2 = 70,broj3 = 144,broj4 = 0,子网掩码= 22,brm = 5)

In第44行,rez将等于01111000 01000110 10010000 00000000(不含空格)。



所以从72行到85,我将rez字符串的3个不同部分分开现在变量b,是我打算与之合作的一部分。

所以在这种情况下,b将是000.



现在我将它转换为十进制(第93行)。现在我需要开始添加一个。

变量n1,告诉我,我需要做多少次(< n1)。

然后b11去是0,1,2,3,4,5,6,7。现在我需要将8个元素中的每个元素转换为二进制,然后转换为具有相同数量的数字的字符串,如起始b为(000)。我有变量n,它告诉我一些事情,其中​​一个是b中的位数。然后那些元素看起来像:000,001,010,011,100,101,110,111。

之后,我带着他们回到主字符串(就像rez那样)这样的东西

rez1 = a + SomethingThatNeedToRepresentThat8Elements(在这种情况下为8)+ c;

然后我将在标签中显示每个元素(rez1)。



之后我正在做更多的事情,但这不是问题的一部分。



所以最后,问题是,我如何使用多个元素一些,比方说,数组(在那部分我多次添加一个,之后用变量做其他一些事情,在这种情况下是b11)?或者更准确地说,如何在C#中完成它,我是否需要多维(动态)数组,或者我必须使用列表或第三类??div class =h2_lin>解决方案

二进制,八进制,十进制,十六进制,罗马和其他任何只是数字的可视表示而不是数字的属性。这就是为什么说二进制数或十进制数(或其他)是没有意义的。只说这是 in 二进制[表示]是有意义的。因此,区分将1添加到二进制数并将1加到十进制数上也没有意义。它只是一样。



前导零甚至只存在于视觉表示中:001 = 1,0000123 = 123.所以说你想要领先零是没有意义的在二进制字符串中表示保留在二进制数中的数字。



因此,您的问题中只有一个真正的要求:如何转换二进制字符串表示某个类型变量的值的数字,可能是一个整数。



这是一个解决方案 - 它还允许在零和一之间放置空格以获得更好的结果可读性。如果您不想允许这样做,请删除switch语句的第一个案例 - 或者使用解决方案2中指出的方法 - 但是在这里您将有'机会'重新演绎如何做到这一点'步骤step':

 命名空间 MyUtility 
{
public static class BinaryLiteral
{
< span class =code-keyword> public static int ToInt32( string str)
{
int bitIndex = 0 ;
int result = 0 ;
for int i = str.Length - 1 ; i > = 0 ; i--)
{
if (bitIndex == 32
throw new OverflowException( 溢出);

switch (str [i])
{
case ' ' break ;
case ' 0' :bitIndex ++; break ;
case ' 1' :result + = 1 << bitIndex处++; break ;
默认 throw new InvalidCastException( 二进制文字中的无效字符: + str [i]);
}
}
返回结果;
}
}
}





用法:

  int  number = BinaryLiteral.ToInt32(  1100 0111); 





编辑(问题更新后v9):



如果我理解正确,这应该做你想要的(在第93行之后插入):

  int  [] b11array =  new   int  [N]; 
for int i = 0 ; i< n; i ++)
b11array [i] = b11 + i;

string [] rezArray = new 字符串 [N];
for int i = 0 ; i< n; i ++)
rezArray [i] = a + Convert.ToString(b11array [i], 2 )。PadLeft(n, ' 0')+ c;


这个问题,如同制定,没有任何意义。数字不能是二进制或不是二进制,它不能是十进制或十六进制,它总是二进制的。只有表示数字的字符串可以有一些任意的基数,但是你已经有了一个字符串。



你可以用这种方式从这样的二进制字符串中获取一个整数:

  string  myString =  //   ... 0100101 ...  
int myValue = System.Convert.ToInt32(myString, 2 );



相反的操作:

  string  bin = Convert.ToString(myValue, 2 ); 



您可以使用这两个转换来添加1:转换,使用+运算符,转换为数字加1。您甚至可以使用字符串,使用通常的学校规则进行添加并将溢出的1带到左侧。我会把它留给你的家庭锻炼。 :-)



-SA


Hello everybody,

I need help about how to convert string to binary number. *But with specific conditions of how that binary number need to looks like.

String which I got is always made by '0' and '1' , something like this '0', '000', '001, '010', '101', '00', '10'(one of that, not all)...

So I need to convert that to binary, but with same amount of 0 and 1 like string had.

And second part of this question is: How I can add one, to that binary number and then to get something like this,
000+1=001,
001+1=010,
010+1=011,
011+1=100 or
00+1=01,
01+1=10...

Btw. it's a WinForm(VisaulStudio), not a console program.

Thanks in advance.

*Question updatet, now it's more precisely about what I'm asking about.
*You can find out more clearly informations about question, in comments down below.


So, first of all, input informations, lets take something like this(There is entire code, so u can understand what I'm talking about.
(http://pastebin.com/mCb99yC7[^])

120.70.144.0/22
5

From this we have(broj1=120, broj2=70, broj3=144, broj4=0, subnetmask=22, brm=5)
In line 44, rez will be equal to 01111000 01000110 10010000 00000000(without spaces).

So from 72 line to 85, I'm separating 3 different parts of rez string. And now variable b, is a part which I'm going to work with.
So in this case, b will be 000.

Now I'm converting it to decimal(line 93). And now I need to start adding one.
Variable n1, is telling me, how many times I need to do it (<n1).
Then b11 going to be 0,1,2,3,4,5,6,7. Now I need to convert, every of that 8 elements to binary, then to string with same amount of digits like starting b was (000). I have variable n, which is telling me few things, one of it is number of digits in b. Then that elements going to looks like: 000,001,010,011,100,101,110,111.
After that, I'm taking them back to main string(like rez was) with something like this
rez1=a+SomethingThatNeedToRepresentThat8Elements(8 in this case)+c;
Then I'm going to show each element(rez1) in labels.

After that I'm doing some more things, but that is not a part of a question.

So at end, question is, how I can work with multiple elements of some, lets say, array(in that part where I'm adding one multiple times, and after that doing some other things with variable, b11 in this case)? Or more precisely, how to do it in C#, do I need multidimensional(dynamic) array, or i must to do it with lists or something third?

解决方案

Binary, Octal, Decimal, Hexadecimal, Roman and whatever else are just visual representations of a number and not properties of a number. That why it makes no sense to speak of a "binary number" or "decimal number" (or whatever). It makes only sense to say "this is a number in binary [representation]". Therefore it also makes no sense to distinguish between adding 1 to a "binary number" and adding 1 to a "decimal number". It's simply the same.

And leading zeroes even only exist in visual representation: 001 = 1, 0000123 = 123. So it makes no sense to say you want leading zeroes in a binary string representation of a number preserved in the "binary number".

Consequentially, there's only one real requirement in your question: How to convert a binary string representation of a number into a value for some type of variable, probably an integer.

Here's a solution for that - it also allows to put spaces between zeroes and ones for better readibility. If you don't want to allow that, remove the first case of the switch-statement - or use the method pointed out in solution 2 - but here you'll have the 'opportunity' to reenact how this can be done 'step by step':

namespace MyUtility
{
    public static class BinaryLiteral
    {
        public static int ToInt32(string str)
        {
            int bitIndex = 0;
            int result = 0;
            for (int i = str.Length - 1; i >= 0; i--)
            {
                if (bitIndex == 32)
                    throw new OverflowException("overflow");

                switch (str[i])
                {
                    case ' ': break;
                    case '0': bitIndex++; break;
                    case '1': result += 1 << bitIndex++; break;
                    default: throw new InvalidCastException("invalid char in binary literal: " + str[i]);
                }
            }
            return result;
        }
    }
}



Usage:

int number = BinaryLiteral.ToInt32("1100 0111");



Edit (after question update v9):

If I understand correctly, this should do what you want (to be inserted after line 93):

int[] b11array = new int[n];
for(int i=0; i<n; i++)
    b11array[i] = b11 + i;
		
string[] rezArray = new string[n];
for(int i=0; i<n; i++)
    rezArray[i] = a + Convert.ToString(b11array[i], 2).PadLeft(n, '0') + c;


The question, as formulated, makes no sense. A number cannot be binary or not binary, it cannot be decimal or hexadecimal, it is always binary. Only a string representing a number can have some arbitrary base, but you already have a string.

You can get an integer from such a "binary string" in this way:

string myString = //... 0100101...
int myValue = System.Convert.ToInt32(myString, 2);


The opposite operation:

string bin = Convert.ToString(myValue, 2);


You can use these two conversions to add 1: convert, add 1 to the number using + operator, convert. You can even do it with strings, using usual school rules for addition and carrying the overflowing 1 to the left. I would leave it to your home exercise. :-)

—SA


这篇关于如何将字符串转换为二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆