2011-01-28 53 views
30

我想在文本框中顯示一個字節。 現在我使用:字節到二進制字符串C# - 顯示全部8個數字

Convert.ToString(MyVeryOwnByte, 2); 

但是,當一個字節是具有0的在begining的被cuted那些0。 示例:

MyVeryOwnByte = 00001110 // Texbox shows -> 1110 
MyVeryOwnByte = 01010101 // Texbox shows -> 1010101 
MyVeryOwnByte = 00000000 // Texbox shows -> <Empty> 
MyVeryOwnByte = 00000001 // Texbox shows -> 1 

我想顯示所有8位數字。

+0

請參閱: http://stackoverflow.com/questions/1644609/c-problem-with-byte和具體http://stackoverflow.com/questions/1644609/c-problem-with-byte/1644666#1644666 – 2011-01-28 14:39:26

+0

作爲在這個代碼問題已經[被另一個用戶誤解了](http://stackoverflow.com/questions/22894695/preceding-0s-in-integer-value),應該指出`MyVeryOwnByte`實際上不是`byte` (如果這是實際使用的C#代碼)文字(例如`01010101`)是* decimal *數字(碰巧只包含零和1);構成這些數字的字節的實際位看起來有點不同。 – 2014-04-06 14:10:09

+0

@ O.R.Mapper它只是「僞代碼」。 – Hooch 2014-04-06 16:01:46

回答

62
Convert.ToString(MyVeryOwnByte, 2).PadLeft(8, '0'); 

這將填充字符串

1

墊字符串用零在總共8個字符的空的空間的左側與「0」。在這種情況下,它是PadLeft(length, characterToPadWith)。非常有用的擴展方法。 PadRight()是另一種有用的方法。

10

你如何去做取決於你希望你的輸出看起來如何。

如果你只是想 「00011011」,使用這樣的功能:如果你想要一個像 「000 」 輸出

static string Pad(byte b) 
{ 
    return Convert.ToString(b, 2).PadLeft(8, '0'); 
} 

,使用這樣的功能:

static string PadBold(byte b) 
{ 
    string bin = Convert.ToString(b, 2); 
    return new string('0', 8 - bin.Length) + "<b>" + bin + "</b>"; 
} 

如果你想輸出像「0001 1011」,這樣的功能可能會更好:

static string PadNibble(byte b) 
{ 
    return Int32.Parse(Convert.ToString(b, 2)).ToString("0000 0000"); 
} 
相關問題