Converting bits in an array to a decimal number [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need a function (in the C language) which can convert the binary contents of an array, in this case myArray[8] {*MSB* 1, 1, 1, 1, 1, 1, 1, 1 *LSB*} into the decimal equivalent = 255.
Any ideas on how to solve this, as efficiently as possible, as it is being done on a microcontroller?

Using bitwise shifting
#include <stdio.h>
int main(void) {
char myArray[8] = {1,1,1,1,1,1,1,1};
int i;
int result = 0;
for (i=0; i<sizeof(myArray); i++){
result += myArray[sizeof(myArray)-i-1] << i;
}
printf("%d\n", result);
return 0;
}

One solution is to add and shift in a Horner scheme.
result = (...((myArray[0])<<1 + myArray[1])<< 1+ ... ) << 1 ... ) + myArray[8];
or in multiple expressions:
result = myArray[0];
result <<= 1;
result += myArray[1];
result <<= 1;
...
result += myArray[8];
This solution is for MSB.

set up the for loop
unsigned int result = myarray[0];
for (int i = 1; i < 8, i++);
{
result <<= 1;
result += myarray[i];
}

#include <stdio.h>
int main()
{
int a[8] = {1,1,1,1,1,1,1,1};
int n=8,dec=0;
int j=0,f;
for(int i=(n-1);i>=0;i--)
{
dec=(a[i]*(int)pow(2,j))+dec;
j++;
}
printf("The converted Decimal number is: %d",dec);
return 0;
}
Output: The converted Decimal number is: 255
The result is also available at: http://ideone.com/NQK0Il

Related

For loop subtraction issue in c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
#include <stdio.h>
int main() {
int a , b, i , sum = 0 ;
printf("\a");
printf("\n\t\t🔸 What is the number you want to begin"
" subtraction with ? ");
scanf("%d",&a);
printf("\n\t\t🔸 What is the number you want to end"
" subtraction with ? ");
scanf("%d",&b);
printf("\a");
printf("\n\t\t🔸 The result of the subtraction of numbers from %d to %d :\n"
, a , b);
printf("\t\t ");
for (i = a ; i >= b+1 ; i--){
printf("%d - ", i);
sum = sum - i ;
printf("%d = %d\n\n", b , sum);
return 0;
}
I want to create a program that subtracts a sequence of numbers from a to b using a for loop in C programming language. I tried for many times, and couldn't find a solution. I want a program that runs like this: for example, if I chose (a) as 8 and (b) as 5, I want the program to write 8-7-6-5 = -10. I want a program that runs like that depending on the value I choose as (a) and (b) using a for loop in c programming.
if I chose (a) as 8 and (b) as 5, I want the program to write 8-6-5 = -3
I believe that you forgot about number 7 and it should be 8-7-6-5 = -10
If yes:
int myfunc(int start, int end)
{
int result = start;
for(int index = start - 1; index >= end; index--)
{
result -= index;
}
return result;
}
int main(void)
{
printf("%d", myfunc(8,5));
}
https://godbolt.org/z/6133cjbK1
If you want to print the whole expression:
int myfunc(int start, int end)
{
int result = start;
printf("%d", start);
for(int index = start - 1; index >= end; index--)
{
printf("-%d", index);
result -= index;
}
return result;
}
int main(void)
{
printf("=%d", myfunc(8,5));
}

Sum of odd numbers using recursion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This might be simple but I'm new to recursion in c. I want to find the sum of odd integers based on user's input. For example if user inputs 3, function returns 9 (1 + 3 + 5 = 9)
int recursiveSumNOdd(int n)
{
int start = -2; //later start = start+2, so it starts at 0
int n1 = n*2; //total number of digits with rec
int num = 0;
int sum=0;
int count=0;
if(start>=n1)
{
return 0;
}
else
{
start = start+2;
count++;
sum = sum +recursiveSumNOdd(start);
}
return sum;
}
Explanations in comment:
int recursiveSumNOdd(int n) {
if (n == 1 || n == 0)// first "if" in a recursive is its stop condition
return n;
return 2 * n - 1 + recursiveSumNOdd(n-1); // formula for 2->3, 3->5 etc
}
int main(void) {
printf("%d\n", recursiveSumNOdd(3));
return 0;
}
NB: You may want to handle integer overflow
NB2: You can have a mathematics formula to return instantly the result, it is way better, but I guess it was to understand better recursion?
return n * n; // the sum of odd numbers is the square of user's input
You are over-complicating things.
You cannot have the sum of negative elements.
int sum_n_odd(unsigned n)
{
What is the sum of 0 (zero) elements?
if (n == 0) return 0;
If you knew the sum of n - 1 numbers, what is the sum of n numbers?
return sum_n_odd(n - 1) + something; // something is easy to figure out
}

Implementation on atoi() function with base [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm going a bit mad implementing this function. I think I have narrow the algorithm down but I have some strange behavior for some value. It seems to work for most of the values and bases, but for string "1000" it simply returns 0.
Below the code:
// A C program for
// implementation of atoi
#include <stdio.h>
#include <stdint.h>
int val(char c)
{
if (c >= '0' && c <= '9')
return (int)c - '0';
else
return (int)c - 'A' + 10;
}
int32_t my_atoi(uint8_t * ptr, uint8_t digits, uint32_t base){
// Initialize result
digits = 0;
// Initialize sign as positive
int sign = 1;
// Initialize index of first digit
int i = 0;
// If number is negative,
// then update sign
if (*ptr == '-') {
sign = -1;
i++;
}
// Iterate through all digits and update the result
for (; *(ptr+i) != '\0'; ++i){
digits = (digits * base) + val(*(ptr+i));
printf("Digits of %d is:%d\n",i,digits);
}
// Return result with sign
return sign * digits;
}
// Driver program to test above functions
int main()
{
uint8_t str[] = "1000";
uint8_t val2=0;
int val = my_atoi(str, val2, 16);
printf("%d \n", val);
return 0;
}
For the above code the output is:
Digits of 0 is:1
Digits of 1 is:16
Digits of 2 is:0
Digits of 3 is:0
0
I simply cannot understand why digits becomes 0 after it has the value 16.
Any help will be greatly appreciated.
Your digits is a uint8_t so it just overflows to 0. You should make it a larger, signed, data type like int32_t or int64_t so the sign works properly and it doesn't overflow.

C program - sum of digits without include the same digit twice [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I do the sum of the digits like that:
while(number>0)
{
sum+=number%TEN;
number=number/TEN;
}
but I need that if the number is (for example) 123444 so it'll include only one 4 in the sum. how can I do that?
Have an array of all digits initialized to zero
int digits[10] = { 0 };
Then before adding a digit you check if digits[that_digit] is zero, if yes you set it to 1 and add to sum, if no keep going ...
while(number>0)
{
int one = number%TEN;
if ( ! digits[one]) {
sum+=one;
digits[one] = 1;
}
number=number/TEN;
}
Edit, no array version
Add an int initialized to 0, the bit i indicates if that digit i has already been summed.
If 1 was added, bit 1 set to 1, if 2, bit 2 set to 1 etc...
int bits = 0;
while(number>0)
{
int one = number%TEN;
if (!(bits & (1<<one))) {
sum+=one;
bits |= 1<<one;
}
number=number/TEN;
}
First you should put some code here whatever you tried, to give you basic idea to solve your problem I am putting simple code below.
#include<stdio.h>
#include<malloc.h>
int main()
{
int input, digit, temp, sum = 0;
printf("Enter Input Number :\n");
scanf("%d",&input);
temp = input;
//first find how many digits are there
for(digit = 0 ; temp != 0 ;digit++, temp /= 10);
//create one array equal to no of digits, use dynamic array because once you find different digits you can re-allocate memory and save some memory
int *p = malloc(digit * sizeof(int));
//now store all the digits in dynamic array
p[0] = input % 10;//1
for(int i = 0; i < digit ;i++) {
input /= 10;
p[i+1] = input %10;
if(p[i] != p[i+1])
sum = sum + p[i];
}
printf("sum of different digits : = %d \n",sum);
free(p);
p = 0;
return 0;
}
Explanation of this code I mentioned in comments itself, it may not work for all test case, remaining try yourself.

C how to check and point a '0' in a int number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Imagine we've got an int number = 1040 or int number = 105 in a C program, and we want to know if this number contains a 0 and in which position/s are they. How could we do it?
Examples
1040 -> position 0 and 2.
1000 -> position 0, 1 and 2.
104 -> position 1.
56 -> NO ZEROS.
Thanks!
I would divide by 10 and check the remainder. If remainder is 0, then last position of the number is 0. Then repeat the same step until number is less than 10
#include<iostream>
int main(void)
{
long int k = 6050404;
int iter = 0;
while (k > 10) {
long int r = k % 10;
if( r == 0) {
std::cout << iter << " ";
}
k = k / 10;
iter++;
}
}
I would convert it to a string; finding a character in a string is trivial.
As a rule of thumb, if you are doing maths on something, it's a number; otherwise, it's probably (or should be treated as) a string.
Alternatively, something like:
#include <stdio.h>
int main(void) {
int input=1040;
int digitindex;
for (digitindex=0; input>0; digitindex++) {
if (input%10==0) {
printf("0 in position %i\n",digitindex);
}
input/=10;
}
return 0;
}
This basically reports if the LAST digit is 0, then removes the last digit; repeat until there is nothing left. Minor modifications would be required for negative numbers.
You can play with this at http://ideone.com/oEyD7N

Resources