Convert string to binary zeros and ones [duplicate

2020-06-04 04:39发布

I want to convert string to binary and I tried this code

byte[] arr = System.Text.Encoding.ASCII.GetBytes(aa[i]);

and this

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] arr= encoding.GetBytes(aa[i]);

but it returned numbers not binary say If I write 'm' it convert it to "0109" and I want to convert to zeros & Ones only Thanks in advance

标签: c# string binary
5条回答
劳资没心,怎么记你
2楼-- · 2020-06-04 05:27

Here is an example:

foreach (char c in "Test")
    Console.WriteLine(Convert.ToString(c, 2).PadLeft(8, '0'));
查看更多
Animai°情兽
3楼-- · 2020-06-04 05:29

You could use : Convert.ToByte(string value, int fromBase)

According to MSDN :

fromBase Type: System.Int32 The base of the number in value, which must be 2, 8, 10, or 16.

For more detail, see this link : Convert.ToByte()

查看更多
▲ chillily
4楼-- · 2020-06-04 05:38

I'm not sure I completely understand your question, but if you want to convert text to binary this is how it is done:

public byte[] ToBinary(string stringPassed)
{
   System.Text.ASCIIEncoding  encoding = new System.Text.ASCIIEncoding();
   return encoding.GetBytes(stringPassed);
}

You need to pass the whole string, not the characters in the string.

查看更多
Melony?
5楼-- · 2020-06-04 05:39

Something like this ought to do you;

static string bytes2bin( byte[] bytes )
{
  StringBuilder buffer = new StringBuilder(bytes.Length*8) ;
  foreach ( byte b in bytes )
  {
    buffer.Append(lookup[b]) ;
  }
  string binary = buffer.ToString() ;
  return binary ;
}

static readonly string[] lookup = InitLookup() ;
private static string[] InitLookup()
{
  string[] instance = new string[1+byte.MaxValue] ;
  StringBuilder buffer = new StringBuilder("00000000") ;
  for ( int i = 0 ; i < instance.Length ; ++i )
  {

    buffer[0] = (char)( '0' + ((i>>7)&1) ) ;
    buffer[1] = (char)( '0' + ((i>>6)&1) ) ;
    buffer[2] = (char)( '0' + ((i>>5)&1) ) ;
    buffer[3] = (char)( '0' + ((i>>4)&1) ) ;
    buffer[4] = (char)( '0' + ((i>>3)&1) ) ;
    buffer[5] = (char)( '0' + ((i>>2)&1) ) ;
    buffer[6] = (char)( '0' + ((i>>1)&1) ) ;
    buffer[7] = (char)( '0' + ((i>>0)&1) ) ;

    instance[i] = buffer.ToString() ;
  }
  return instance ;
}
查看更多
干净又极端
6楼-- · 2020-06-04 05:41

So you can get to bytes, now you want to output 0s and 1s.

For a single byte b

var sb = new StringBuilder();
for(var i=7;i>=0;i--)
{
  sb.Append((b & (1<<i))==0?'0':'1');
}
查看更多
登录 后发表回答