Convert an integer to binary without using the built-in bin function

后端 未结 15 1395
深忆病人
深忆病人 2020-12-07 01:14

This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the l

15条回答
  •  有刺的猬
    2020-12-07 01:18

    You can first use the format function to get a binary string like your current function. For e.g the following snippet creates a binary string of 8 bits corresponding to integer 58.

    >>>u = format(58, "08b")
    '00111010'
    

    Now iterate the string to convert each bit to an int to get your desired list of bits encoded as integers.

    >>>[int(d) for d in u]
    [0, 0, 1, 1, 1, 0, 1, 0]
    

提交回复
热议问题