Groups,
Take a look at the following program taken from C snippet archive.
-----------------------code------------------------
void bitstring(char *str, long byze, int biz, int strwid)
{
int i, j;
j = strwid - (biz + (biz >> 2)- (biz % 4 ? 0 : 1));
for (i = 0; i < j; i++)
*str++ = ' ';
while (--biz >= 0)
{
*str++ = ((byze >> biz) & 1) + '0';
if (!(biz % 4) && biz)
*str++ = ' ';
}
*str = '\0';
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char s[80]; long j;
for (j = 1L; j <= 16L; j++)
{
bitstring(s, (long)j, (int)j, 16);
printf("%2ld: %s\n", j, s);
}
return EXIT_SUCCESS;
}
------------------------output--------------------
1: 1
2: 10
3: 011
4: 0100
5: 0 0101
6: 00 0110
7: 000 0111
8: 0000 1000
9: 0 0000 1001
10: 00 0000 1010
11: 000 0000 1011
12: 0000 0000 1100
13: 0 0000 0000 1101
14: 00 0000 0000 1110
15: 000 0000 0000 1111
16: 0000 0000 0001 0000
--------------------------------------end--------------------
My doubts are:
1) In the expression
j = strwid - (biz + (biz >> 2)- (biz % 4 ? 0 : 1));
the variable biz is right shifted. When I looked at the called
function (which happens to be main()) the loop(var j) iterates from 1 to 16.
Then that must defiantly crosses the value 3. According to the std 99, 6.5.7.3
"....If the value of the right operand is negative or is
greater than or equal to the width of the promoted left operand, the
behavior is undefined."
Does the above invokes UB? How shall I interpret the word *width* in the
statement. Does statement considered the value only or the sizeof the left operand.
2)Why the number 4 is been used in the MOD operator?Is it a magic number?
3) Does the variable biz is changed more than once between the sequence point?
<OT to comp.lang.c>
Can anybody explain the function bitstring(). I took a paper and pen, I am not able to proceed
further.
</OT to comp.lang.c>