Reputation: 131
Is there a way to convert an array to an integer, i have the follow method but it does not seem to work:
int8_t x_array[18] = {0,1,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1};
int32_t numb;
for (int8_t j=0;j<19;j++)
{
numb = numb + pow(2, i)*x_array[i];
}
Is there a reason for this??
PS: this is a follow up question from a previous question I had posted Joining outputs from switches I have edited the question to say why the method suggested is not working.
In essence what I am trying to do is create a program, in RAPIDILITTE which is a simulator software, to sample a PS input (proximity sensor system) every millisecond which is 18-bit digital input. The input is represented by toggle switches 0-17(18-bits) which is located on port 2. the input need to be normalised between 0-9999)
The main problem is that( which I have mentioned in the previous posted question) I can only access one pin at a time and not the read the whole port at once. I have tried many ways to read the pins and combine them into one variable convert it to a natural number and then normalise the input. In the end I believe the best way to do this is to put the each pins reading into a array[18]
and then covert this into a variable and then normalise it.
Upvotes: 0
Views: 161
Reputation: 7752
As the other guys mentioned, your problem is that you have not initilized numb and that leads to undefined bahaviour of your program.
Also you're loop counter needs to be changed to i
rather than j
!
I just wanted to add one other modification to your program and that's how you've been calculating the final result. How about this ? It need much less operation to get the answer :
numb = 0;
for (int8_t i=LEN;i>0;i--)
numb = numb*2 + x_array[i-1];
Upvotes: 0
Reputation: 29646
numb
is never initialized. You're also iterating past the last element in the array (j < 19
should be j< 18
). Additionally, you never declared i
... it appears you meant j
.
I believe you're trying to convert the array of bits into a single int32_t
. Presumably the array is in ascending order of significance i.e. from least- to most-significant bit.
int8_t x_array[18] = { 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1 };
int32_t numb = 0;
for (int8_t j = 0; j < 18; ++j) {
numb |= x_array[j] << j;
}
You don't need to use pow
here, since pow(2, j)
is equivalent to 1 << j
.
Upvotes: 1
Reputation: 477040
You never initialize your variable, so reading it is plain undefined behaviour. You should say:
int32_t numb = 0;
You should also decide whether you want i
or j
as your loop variable.
(Computing the power each time is also wasteful; instead, you should keep a running multiplier and double it at each step.)
Upvotes: 3