# Converting input integer value to binary

Page 1 of 1

## 4 Replies - 2498 Views - Last Post: 30 November 2011 - 02:37 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=257844&amp;s=869e0e034bcd70a8d68187d17caa8fab&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 pvpkiller

Reputation: 0
• 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

Reputation: 452
• Posts: 797
• 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

```

### #3 pvpkiller

Reputation: 0
• 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?

### #4 Motoma

Reputation: 452
• Posts: 797
• 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'

```

### #5 pvpkiller

Reputation: 0
• 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