Join the social network of Tech Nerds, increase skill rank, get work, manage projects...

• # Conversion of binary value to an integer

• 0
• 0
• 0
• 0
• 0
• 0
• 0
• 0
• 2.14k
Comment on it

### Description:

Given an array of one's and zero's convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1

Examples:

``````Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11``````

### Solution :

Ruby

``````def binary_array_to_number(arr)
arr.join("").to_i(2)
end ``````

#### JavaScript

``````const binaryArrayToNumber = arr => {
return (arr[0] * 8) +
(arr[1] * 4) +
(arr[2] * 2) +
(arr[3] * 1);
};``````

### Test Cases: Ruby

``````Test.describe("Example tests") do
Test.assert_equals(binary_array_to_number([0,0,0,1]), 1)
Test.assert_equals(binary_array_to_number([0,0,1,0]), 2)
Test.assert_equals(binary_array_to_number([1,1,1,1]), 15)
Test.assert_equals(binary_array_to_number([0,1,1,0]), 6)
end
Test.describe("Random tests") do

def randint(a,b) rand(b-a+1)+a end

50.times do
n = randint(0,1000)
array = n.to_s(2).split("").map(&:to_i)
Test.it("Tests #{array} ==> #{n}") do
Test.assert_equals(binary_array_to_number(array), n, "It should work for random inputs too")
end
end
end``````

## 0 Comment(s)

OR
OR
Register

OR
Fill out the form below and instructions to reset your password will be emailed to you:

• Hire
• Post Projects

### Post Projects

• All at 0 Cost ....
• Post Tech Job
• Select Best Bidder
• Track the Project
• Approve Work and Pay safely
• Browse Nerds
• Work
• Find Projects Find Projects
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
View more...
View less...
• Manage
• Company Company

### Manage Company

• All at 0 Cost ....
• Manage Company and Employee Profiles
• Company wide Employee Productivity Reports
• Knowledge Sharing and Collaboration Tools
• Get Sales Lead and Bid for Tech Projects
• Send Invoices and Receive Payment Safely
• Learn
• Nerd Digest Nerd Digest
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
View more...
View less...
• Tech Q & A Tech Q & A
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
View more...
View less...