简体   繁体   中英

Convert Byte To String

I would like to convert a byte to a string.

Example:

byte testByte = 0x05;

testByte should be converted to "00000101"

I have tried Convert.ToString(testByte, 2), but it only returns "101"

您已经非常接近了,您需要做的就是在已经生成的String上调用PadLeft

Convert.ToString(testByte, 2).PadLeft(8,'0');
static string ToBase2String(int n, int pad)
{
    var s = n < 0 ? "-" : "";
    var v = n < 0 ? -n : n;

    while (v > 0)
    {
        s = (v % 2 == 0 ? "0" : "1") + s;
        v /= 2;
    }

    return s.PadLeft(pad, '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