4-bit number to decimal number

1.9k Views Asked by At

Juts like the title says: a code to convert a 4-bit number into a decimal equivalent number without using any fucntion from octave's library. Not a clue!

We consider the input a binary number (example: 0001, 1010) to decimal number as a output.

3

There are 3 best solutions below

1
On

Recall what each location in the binary form represents: the locations of the 1's describe which powers of two make up the number. For a 4-bit number, the 4 locations represent $2^3$, $2^2$, $2^1$, and $2^0$, in that order (increasing powers of two from right to left). Thus in your example,

0001: $2^0 = 1$

1010: $2^3 + 2^1 = 8+2 = 10$

So, for the code, a simple way is to loop through the elements of the binary number, and if that element is 1, add it to your number,

x = [0 0 0 1];
n = length(x);
y = 0;
for i = 1:n
    if x(i)
        y = y + 2^(n-i);
    end
end
0
On

One stupid way: let the input be $n$. I don't know octave, so consider this pseudo-code. Usually constants in programming languages are in base $10$
If n=0, output "0"
If n=1, output "1"
etc

Presumably you need to output a string.

Another similar idea. Define an array out as ["0","1","2" ,\dots "15"] Print out(n)

0
On

If your input is a binary number, x2, entered in decimal format, this should work:

x10=0; for i=3:-1:0 d=floor(x2/10^i); x2=x2-d*10^i; x10=x10+d*2^i; end

x10 will be the decimal representation you want.