Skip to main content
1-Visitor
April 11, 2016
Solved

How to convert from binary number (vector form) to decimal (with Prime)?

  • April 11, 2016
  • 4 replies
  • 4182 views

Greetings.

I need convert binary numbers and show the process, for example:

The binary 1011 is the matrix vector [1 0 1 1], need a program that make 2^3, 0^2, 2^1 and 2^0 then show a matrix [8 0 2 1] and later the sum 11 (8+2+1).

Need show the matrix and sum, working according to the number of digits.

Also need convert (based on block of 3 and 4 digits of) binary number to octal and hexa numbers.

Best answer by Werner_E

Valery Ochkov wrote:

Sorry.

for i=ORIGIN to last(x) - ORIGIN

NO! Definitely not. That would be one or more too few, if ORIGIN>0.

But thanks, because you are right, that I made a mistake in this respect ( I should have tried using a value for ORIGIN different to 0).

We can correct it in different way. I guess the way I have chosen in cdec2 is the better one:

As a bonus I added the ability to provide the argument either as a row vector OR as a simple scalar.

Werner

4 replies

25-Diamond I
April 11, 2016

The problem is, that when you use the column-selector, you get a 1x1 matrix, bot a scalar.

You can't compare a 1x1 matrix to a scalar like 1 or 0.

Use something like x[0,i instead.

Furthermore you program has no return value and the while loop will rund endless, as i never changes inside that loop.

Not clear what you try to do with x[i]<--x[i] in that "try and catch".

WE

24-Ruby IV
April 11, 2016

May be so?

25-Diamond I
April 11, 2016

Looks like you also want to see the powers of 2 as intermediate result and you also tried to implement some error handling.

Maybe you were looking for something like this:

24-Ruby IV
April 11, 2016

Sorry.

for i=ORIGIN to last(x) - ORIGIN

Werner_E25-Diamond IAnswer
25-Diamond I
April 11, 2016

Valery Ochkov wrote:

Sorry.

for i=ORIGIN to last(x) - ORIGIN

NO! Definitely not. That would be one or more too few, if ORIGIN>0.

But thanks, because you are right, that I made a mistake in this respect ( I should have tried using a value for ORIGIN different to 0).

We can correct it in different way. I guess the way I have chosen in cdec2 is the better one:

As a bonus I added the ability to provide the argument either as a row vector OR as a simple scalar.

Werner

23-Emerald V
April 11, 2016

rking-2 wrote:

I need convert binary numbers and show the process, for example:

The binary 1011 is the matrix vector [1 0 1 1], need a program that make 2^3, 0^2, 2^1 and 2^0 then show a matrix [8 0 2 1] and later the sum 11 (8+2+1).

Need show the matrix and sum, working according to the number of digits.

Also need convert (based on block of 3 and 4 digits of) binary number to octal and hexa numbers.

Here's another approach to the conversion from a binary digits vector to a vector of powers and sum - works with any base, not just binary ...