hi,

with this code fragment:

#include <stdio.h>

void print_bit_string(char x)
{
	int s = 128;
	for (int i = 0;i < 8;i++)
	{
		printf("%d",x & s? 1: 0);
		s >>= 1;		
	}
	printf("\n");
}

char abs(char x)
{
	if (x < 0)
	{
		x = -x;
	}
	return x;
}

int main()
{
	char x = -1;
	printf("x: %d abs: %d\n",x,abs(x));
	print_bit_string(abs(x));
	x = -128;
	printf("x: %d abs: %d\n",x,abs(x));
	print_bit_string(abs(x));
	return 0;
}

why the output is as follows?

x: -1 abs: 1
00000001
x: -128 abs: -128
10000000

On line 8 print the value of s on each iteration of the loop then you can see why you get that output. If you use a scientific calculator you will see that (1 & 128) is 0. Then 128 > 1 is 64. (1 & 64) = 0. 64 > 1 = 32. etc.

Consider the range of char. Also, abs is a reserved identifier.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.