Implementation on atoi() function with base [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 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.

Related

Wrote a program to get the binary output of a decimal, and the result is inverted [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
Below is the program for my assignment. All of it was given except the printing and logic. I searched many videos about it and did what they did, but 15's binary is 1111 and the result was 0000
#include <stdio.h>
#include <math.h>
// Function to convert decimal to binary
// The function is void type so, print the result inside the function
void decimal2Binary(int dec) {
// array to store binary number
int binaryNumber[32];
// Your logic goes here
// fill out the binaryNumber
// i to increment the loop and terminate
int i = 0;
// We are interested in positive numbers for now
while (dec > 0) {
// Please add your logic to build the binary array
binaryNumber[i] = dec%2;
dec = dec/2;
i++;
}
// Print the binary array.
printf("Binary: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d",binaryNumber[i]);
}
}
// The main function goes here
// The main function calls the decimal2Binary
int main() {
int decimal = 15;
printf("Decimal: %d equal to ", decimal);
decimal2Binary(decimal);
return 0;
}
DECIMAL TO BINARY (RECURSIVE):
#include <stdio.h>
int find(int dec_num)
{
if (dec_num == 0)
return 0;
else
return (dec_num % 2 + 10 *
find(dec_num / 2));
}
int main()
{
int decimal_number;
scanf("%d", &decimal_number);
printf("%d", find(decimal_number));
return 0;
}
DECIMAL TO BINARY (ITERATIVE):
#include <stdio.h>
long dec_to_bin(int decimalnum){
int binarynum = 0;
int mod, place = 1;
while(decimalnum != 0){
mod = decimalnum % 2;
decimalnum = decimalnum/2;
binarynum = binarynum + (mod*place);
place = place*10;
}
return binarynum;
}
int main() {
int decimalnum;
scanf("%d", &decimalnum);
printf("enter a decimal number:\n %ld", dec_to_bin(decimalnum));
return 0;
}

How can I print the base two representation of a number without using any array 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 2 years ago.
Improve this question
I need to print my characters BEFORE the previously printed character using printf. For example:
printf("1")
printf("0")
would need to output:
01
Is there a way to do this? I cannot use arrays. To be clear I'm printing in base two (binary) representation using a divide by two algorithm:
for(int i = 0; i < 16; i++){ // 16 bit int
tmp = num % 2;
if(tmp == 1){
printf("1");
} else {
printf("0");
}
num /= 2;
}
The above code prints the binary representation backwards.
Here is my solution to print binary without using array. you can ignore initial zeros by adding another if condition.
#include<stdio.h>
int main(){
int num =50;
int i;
for(i=15;i>=0;i--){
if( (1<<i) & num){
printf("1");
}
else printf("0");
}
return 0;
}
output:
0000000000110010
Recursion can perform like a "print before". #rici
The below does not always print 16 digits, just the decimal digits needed.
void print_binary(unsigned n) {
// Break the digits into 2 groups: 1) the one least digit and 2) the rest.
unsigned last_digit = n/10;
unsigned all_the_other_more_significant_digits = n/10;
// Let us print those more significant digits first;
if (all_the_other_more_significant_digits > 0) {
print_binary(all_the_other_more_significant_digits);
}
// Now print the last digit
printf("%u", last_digit);
}

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.

Converting bits in an array to a decimal 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 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

function check short int algorithm [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 9 years ago.
Improve this question
This is my function and I need help....
I must try to catch the range of short int without error handler or try&catch.
I cant´t find my failure in this algorithm — I hope you can help me.
short int checkShortInt(char * myString)
{
short int i = 0;
short int len;
if((myString[i]=='+')||(myString[i]=='-')) i++;
for (len = i; myString[len] != '\0'; len++);
if(len-i>5) return(0);
if(myString[i+0]<'3') return(1);
if(myString[i+0]>'3') return(0);
if(myString[i+1]<'2') return(1);
if(myString[i+1]>'2') return(0);
if(myString[i+2]<'7') return(1);
if(myString[i+2]>'7') return(0);
if(myString[i+3]<'6') return(1);
if(myString[i+3]>'6') return(0);
if(myString[i+4]>'7') return(0);
return(1);
}
Note that the range covered by short is asymmetric when two's complement is used: it normally ranges from -32768 to 32767.
If the length of the value is smaller than 5, the string clearly fits into a short.
My two cents. Maybe overkill...
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <inttypes.h>
int checkShortInt(char *myString)
{
long long i = strtoll(myString, 0, 0);
return (i >= SHRT_MIN && i <= SHRT_MAX);
}
short int checkShortInt(char * myString)
{
short int i = 0;
int total = 0;
// Skip a leading +/- sign.
if((myString[i]=='+')||(myString[i]=='-')) i++;
while(myString[i] != '\0')
{
total = 10*total + myString[i]-'0';
++i;
}
if (SHRT_MIN <= total && total <= SHRT_MAX)
{
return total;
}
return 0;
}
Sample inputs and results:
checkShortInt("53") ==> 53
checkShortInt("+125") ==> 125
checkShortInt("0") ==> 0
checkShortInt("70345") ==> 0

Resources