M
Mark
I need to print out a bits layout of 32-bit register, where bits 0-24
represent a network port's status (bit 1 is for up and 0 for down) and
others are not used. Simply printing each bit in a loop works fine, but I'd
like to write it in a buffer with formatted output, and this where I stuck:
puts("Group Ports");
puts(" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
22 23 24");
puts("-----------------------------------------------------------------------------");
uint32_t val = 0x1234567; /* for this example */
char buf[66] = " "; /* 6 spaces */
int i, m = 0;
for (i = 0; i < sizeof(val) * CHAR_BIT; i++) {
/* 10 is left margin of spaces in the above string */
/* I have to smoothly move along the buffer to print 1 or 0
according to the port's number */
m += snprintf(buf + 10 + m, sizeof(buf), (val & 0x00000001) ? "1 " :
"0 "); /* XXX */
val = val << 1;
}
fprintf(stdout, "%s\n", buf);
This code is very clumsy and, in my understanding, XXX invokes underfined
behavior, because 'm' is used in two sequence points?
What would you recommend to improve/change to make it look clean and solid?
represent a network port's status (bit 1 is for up and 0 for down) and
others are not used. Simply printing each bit in a loop works fine, but I'd
like to write it in a buffer with formatted output, and this where I stuck:
puts("Group Ports");
puts(" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
22 23 24");
puts("-----------------------------------------------------------------------------");
uint32_t val = 0x1234567; /* for this example */
char buf[66] = " "; /* 6 spaces */
int i, m = 0;
for (i = 0; i < sizeof(val) * CHAR_BIT; i++) {
/* 10 is left margin of spaces in the above string */
/* I have to smoothly move along the buffer to print 1 or 0
according to the port's number */
m += snprintf(buf + 10 + m, sizeof(buf), (val & 0x00000001) ? "1 " :
"0 "); /* XXX */
val = val << 1;
}
fprintf(stdout, "%s\n", buf);
This code is very clumsy and, in my understanding, XXX invokes underfined
behavior, because 'm' is used in two sequence points?
What would you recommend to improve/change to make it look clean and solid?