Unsigned char is printing -ve answer when printed in binary [closed] - c

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 7 years ago.
Improve this question
Objective is to print binary output of -ve or +ve integers and output is correct when we declare variable with signed, but not able to understand the behaviour when variable is declared as unsigned.
int main() {
unsigned char num = -1; /* unsigned int */
int i = 0;
/* Loop to print binary values */
for (i = 0 ; i < 8; i++) {
if(num & 128u)
{
printf("1 ");
}
else
{
printf("0 ");
}
num= num<<1;
}
printf("\n");
return 0;
}
output is printed as "1 1 1 1 1 1 1 1"
which is equal to -1; But i have given unsigned int as input. How this works?

When you doing
unsigned char num = -1; /* unsigned int */
It storing in num is 255 (Max Number) in decimal. So in every loop if(num & 128u) is satisfying so the o/p is ....
/* output is printed as "1 1 1 1 1 1 1 1" */
There are some more mistakes in question you are saying abot int but in program you have taken char variable and storing signed number in unsigned variable so , you will not get o/p what you expect.

Related

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);
}

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.

What is the logic is used in this program [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 6 years ago.
Improve this question
A 5 digit positive number is entered by user.how to calculate the sum of the Digits entered by the user with the help of function?
We beginners should help each other.:)
Here you are.
#include <stdio.h>
unsigned int digits_sum( unsigned int value )
{
const unsigned int Base = 10;
unsigned int sum = 0;
do { sum += value % Base; } while ( value /= Base );
return sum;
}
int main( void )
{
unsigned int value = 12345;
printf( "The sum of digits of number %u is %u\n", value, digits_sum( value ) );
return 0;
}
The program output is
The sum of digits of number 12345 is 15
The logic is simple. To get the last digit of a number you should apply operator %. Then you need to divide the number by 10 that in the next step to get the digit before the last and so on.

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