简体   繁体   中英

Get 8 digit binary from char in c# win. form

How to get 8 digit binary from char in c# win. form?

Like if i write D it should return 01000100 and if i write T it should return 01010100

char c = 'D';
string s = Convert.ToString(c,2); // results in "1000100"
string s2 = s.PadLeft(8, '0'); // results in "01000100"

OP asked for a faster solution, so I suggest a pre-calculated lookup table

string[] binaries = new string[256];

// Calulate all 8 bit decimal string representations. 
// Do this once, on initialization.
for(int i = 0; i < 256; i++)
{
    binaries[i] = Convert.ToString(i,2).PadLeft(8, '0');
}

// Get the representation for a character.
char c = 'D';
string s = binaries[c];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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