简体   繁体   中英

Converting a hex value to byte with 8 digits in C#

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.

其实你要正确对待_dataRx (比如, "255"作为小数点 ,而不是十进制值( 0x255 == 597 == 1001010101 (binary)255 == 0xFF = 11111111 (binary)要求):

string x = Convert.ToString(int.Parse(_dataRx), 2).PadLeft(8, '0');

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