Converting a whole number to base 2 (Binary Operation)

조회 수: 2 (최근 30일)
Hmm!
Hmm! 2021년 1월 15일
답변: Walter Roberson 2021년 1월 15일
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.

답변 (1개)

Walter Roberson
Walter Roberson 2021년 1월 15일
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.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by