How to extract operand size in bits of a C program?

Hi I'm new to shell programming. How do I extract the size of an operand in a simple instruction in a C program? Lets say there is an addition a+b somewhere in a C code where a and b are integers. How to extract the size of a & b in bits? Is there something called intermediate code before an executable code which shows these details?

You don't find the number of bits in the result of adding two values in a C program in the shell; you find that number in your C program. And, the number of bytes in the result of an addition depends on the sizes of the integers you are adding. Due to integral value promotion rules in C on a UNIX-, Linux-, or BSD-based operating system, the number of bits in the result of adding a and b will be the number of bits in the largest of the two values a and b. The number of bytes in a can be found with sizeof(a); and the number of bytes in b can be found with sizeof(b); and the number of bits in the result will be 8 times the maximum of those two sizes.

1 Like

I thought of a method to find out exact no. of bits in a operand. Right shifting by 1 bit until it becomes zero. No. of times shifted will be size of the operand. But how do I write a shell script to do this?

OK. That is a different question totally unrelated to the title of this thread. The highest bit set in a non-negative integer number for a number that will fit in a C signed long integer value can be found in a shell that conforms to the POSIX standards using something like:

printf 'Enter non-negative integer (ctl-D to exit): '
while read -r n
do	printf 'Highest bit set in %s is ' "$n"
	bits=0
	while [ "$n" -gt 0 ]
	do	bits=$((bits + 1))
		n=$((n / 2))
	done
	printf '%d.\n' $bits
	printf 'Enter another non-negative integer (ctl-D to exit): '
done
printf '\nGoodbye\n'

Of course, this doesn't do any validity checking on the values entered and may die a horrible death if a non-numeric entry or an out-of-range numeric entry is given. With a 1993 or later version of the Korn shell, you might be able to process numbers considerably larger than 2**63 - 1.

1 Like

Thank you very much for helping me who had no idea of doing this :slight_smile: