Converting a whole number to base 2 (Binary Operation)

5 views (last 30 days)
I know there are built in functions for converting a decimal and whole numbers to binary numbers.
But I need help in writting a function: A = bin(n), that converts a positive, whole number (n) into binary format,
let say n=12. Please, I am a newbie in matlab trying to get a way around coding, so pardon me for naiveness.
A is an array of appropriate length that contains values of 1 and 0.
Thank you in advance.

Answers (1)

Walter Roberson
Walter Roberson on 15 Jan 2021
Consider 19 as an example.
19 is odd, which is to say that the remainder when divided by 2 is 1. Write down the 1, subtract it from 19 to get 18, divide 18 by 2 to get 9. -> 1.
9 is odd. Write down the 1 to the left of the previous 1, subtract it from 9 to get 8, divide 8 by 2 to get 4. -> 11.
4 is even, which is to say that the remainder when divided by 2 is 0. Write down the 0, subtract it from 4 to get 4, divide 4 by 2 to get 2 -> 011.
2 is even. Write down the 0, subtract it from 2 to get 2, divide by 2 to get 1 -> 0011.
1 is odd. Write down the 1, subtract it from 1 to get 0, divide by 2 to get 0 -> 10011
0 reached. Stop. Final result is 10011 which is 16+3 which is 19, so cross-checking shows we got the correct representation.
I have given enough clues that you should be able to construct the algorithm and turn that into code.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!