Computer Science Canada

converting decimal to binary using functions

Author:  tooring [ Tue Oct 23, 2007 8:01 pm ]
Post subject:  converting decimal to binary using functions

i have a fairly good understanding of functions, but i have no clue on how to start this.

im thinking of doing it by getting each number, and using its modulus, and printing it out, but
i need to have it so that it displays the binary output in numbers of 8

How would I do each number say if the user enters 845, getting 5, then 4, then 8, and depending on
how many number inputed, it would only do it for that many numbers.

such as 2 would be 00000000 00000000 00000000 00000010

any help would be greatly appreciated

Author:  md [ Tue Oct 23, 2007 9:37 pm ]
Post subject:  RE:converting decimal to binary using functions

let n be an integer
n % 2 will return the last binary digit
n >> 1 will shift n one to the right (dropping the last binary digit)

thus you just need to loop 32 times, saving n%2 and then shifting n one to the right. At the end you can format your string however you want.

Author:  tooring [ Wed Oct 24, 2007 6:37 am ]
Post subject:  Re: converting decimal to binary using functions

would i use a for loop to save it 32 times?
i'll post up a code of what I have so far


: