4 Replies - 1698 Views - Last Post: 30 November 2011 - 02:37 PM Rate Topic: -----

#1 pvpkiller  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 24-June 11

Converting input integer value to binary

Posted 30 November 2011 - 12:06 PM

Okay, so this is the problem I have. I have to convert an integer value, given by the user, into binary strings, but the length is also specified by the user. The integers are non negative. I was thinking of using the built in function in python, bin(x), but that won't help because the user has to specify the length of the binary string.

def convert_to_binary(value, length):



Any help is appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: Converting input integer value to binary

#2 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • Joined: 08-June 10

Re: Converting input integer value to binary

Posted 30 November 2011 - 12:31 PM

Use bin() and then resize it as necessary?

Or use the divide by 2 method. Pseudocode:
binary_string = ""
while number != 0:
    if number is divisible by two:
        prepend "1" to binary_string
    else:
        prepend "0" to binary_string
    integer divide number by 2
prepend "0"s until binary_string is the right length


Was This Post Helpful? 1
  • +
  • -

#3 pvpkiller  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 24-June 11

Re: Converting input integer value to binary

Posted 30 November 2011 - 01:57 PM

wait, what do you mean by re-size it as necessary? I can use the bin() function, but how do i re-size it? Using a list and slicing it?
Was This Post Helpful? 0
  • +
  • -

#4 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • Joined: 08-June 10

Re: Converting input integer value to binary

Posted 30 November 2011 - 02:26 PM

A quick example:
>>> fivehundred = bin(500)
>>> fivehundred
'0b111110100'
# All but the first two characters ("0b")
>>> fivehundred = fivehundred[2:]
>>> fivehundred
'111110100'
>>> len(fivehundred)
9
# Pad to 12 characters (12 - 9 = 3)
>>> fivehundred = '0' * 3 + fivehundred
>>> fivehundred
'000111110100'
# Trim to 4 characters
>>> four = fivehundred[-4:]
>>> four
'0100'


Was This Post Helpful? 1
  • +
  • -

#5 pvpkiller  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 24-June 11

Re: Converting input integer value to binary

Posted 30 November 2011 - 02:37 PM

Thanks, I got it now, works great :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1