Skip to main content

functions - How to use summation to get the value of a binary number?


How to use summation to get the value of a binary number?


I want to do this:



$(x_{n}x_{n-1}...x_{0})=\sum_{i=0}^{n}x_{i}\cdot b^{i} $


But it seems that I can only do something like this:


$\sum_{i=1}^{10}i^{2}$


I imagine that there is some indexation function which will help to do so, I also know how to do in another way, but is it possible to do this using summation?



Answer



binDigits = {1, 0, 1, 1, 1, 1, 1, 0};

Alternative 1:


binDigits.Table[2^i, {i, Length[binDigits] - 1, 0, -1}]


(* ==> 190 *)

Alternative 2:


Sum[2^(Length[binDigits] - i) binDigits[[i]], {i, Length[binDigits]}]

(* ==> 190 *)

Alternative 3:


FromDigits[binDigits, 2]


(* ==> 190 *)

If your binary number is given as a string you could do the following first:


binDigits = ToExpression /@ Characters["10111110"]

(* ==> {1, 0, 1, 1, 1, 1, 1, 0} *)

If your binary number is given as a decimal numbers with 1's and 0's only (actually a misrepresentation) you could try:


binDigits = ToExpression /@ Characters@ToString@10111110


(* ==> {1, 0, 1, 1, 1, 1, 1, 0} *)

Comments