Reputation: 982
I receive a value of "7". Using my code below. I get "111" but what I need is "0000111" and if I receive "255" I get "1001010101" but what I need to get is "11111111". Please see my code below:
_dataRx = ((SerialPort) (sender)).ReadLine();
_dataRx = _dataRx.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
var x = Convert.ToString(Convert.ToInt32(_dataRx, 16), 2);
Console.WriteLine(x);
I need to have 8 digits always since I need to place it in an array. Can you please help. Thank you.
Upvotes: 1
Views: 820
Reputation: 186668
Actually you want to treat _dataRx
(say, "255"
) as a decimal, not hexadecimal value (0x255 == 597 == 1001010101 (binary)
when 255 == 0xFF = 11111111 (binary)
required):
string x = Convert.ToString(int.Parse(_dataRx), 2).PadLeft(8, '0');
Upvotes: 6