I am a beginner in C and wish to know how to convert an array of numbers that represent the bits of a number into the integer it represents.
I searched online but only found char array to int.
I am making converter and need to int array to toggle the bit values from 1 to 0 and vice versa(ie binary). So far i have managed to make the array integers toggle, but I cannot figure out how to change the array of numbers into the single number the array represents. I need this integer so i can convert it into a decimal number which the user can view.
Is there any simple solution to this?
bin= integer variable to store the binary number
arrbin = integer array to store the state of the bit ie(00000000)
for (i = 0; i < 8; ++i )
{
bin = bin + (10 * arrbin[i]);
}
EDIT: I think i see the problem now, instead of the values being implemented every exponent of 10 up, the numbers were only being multiplied by 10. will try and see if this fixes it.
EDIT #2: I dont mean conversion of binary to decimal. I meant conversion of array of numbers ie{1,0,0,0,0,0,0,1) to integer (integer varible = 10000001 not 129)
Steps of implementation are: Traverse the whole array. For each number, declare and initialize a variable "temp" to 0, which stores the number of set bits for the current number. Run a while loop until the number becomes 0. If the current last bit is set, add one to the temp.
You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.
To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order. Here is an example of such conversion using the integer 12.
To convert an array of strings to an array of numbers, call the map() method on the array, and on each iteration, convert the string to a number. The map method will return a new array containing only numbers.
You basiclly have the answer but you would be better doing it from the other direction ie:
int multiplier = 1;
for (i = 7; i >= 0; --i )
{
bin += (multiplier * arrbin[i]);
multiplier *= 10;
}
that way you can change the length of the array you are using easily.
How about do it manually, the same way you do it to convert binary to int using powers of 2
#include <stdio.h>
#include <string.h>
main()
{
int arr[4]={1,0,0,1};
int i;
int output=0, power=1;
for (i=0; i<4; i++)
{
output += arr[3-i]*power;
power *= 2;
}
printf("%d\n", output);
in this example
arr = 1 0 0 1
output = 1*2^0 + 0*2^1 + 0*2^2 + 1*2^3 = 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With