same code pelles c and gcc got different results.

Started by ander_cc, March 15, 2026, 11:30:22 AM

Previous topic - Next topic

ander_cc

#include <stdio.h>
#include <stdbit.h>
int main() {
    unsigned short a1 = 4;
unsigned int a2 = 4;

printf("a1 one:%u  a1 zero:%u\n", stdc_first_leading_one(a1), stdc_first_leading_zero(a1));
printf("a2 one:%u  a2 zero:%u\n", stdc_first_leading_one(a2), stdc_first_leading_zero(a2));
   
    return 0;
}
gcc 11.4 -std=c23
a1 one:14  a1 zero:1
a2 one:30  a2 zero:1
-----
pelles c 13.01
a1 one:3  a1 zero:16
a2 one:3  a2 zero:32
-----
WHY? and which is right?

rweidner

I didn't know the answer to this question. I asked ChatGPT.

QuoteChatGPT:

Assuming the usual widths on a typical modern desktop/compiler:

unsigned short = 16 bits

unsigned int = 32 bits

stdc_first_leading_one(x) returns the 1-based position of the first 1 when scanning from the most-significant bit (MSB).
stdc_first_leading_zero(x) returns the 1-based position of the first 0 when scanning from the MSB.

For 4, the bit pattern is ...00000100 (only bit 2 set, counting from LSB starting at 0):

First leading one is at position width - 2

First leading zero is at position 1 (because the MSB is 0 for the value 4)

So the output will be:

a1 one:14  a1 zero:1
a2 one:30  a2 zero:1

Explanation:

a1 (16-bit): 16 - 2 = 14

a2 (32-bit): 32 - 2 = 30

If you run this on a platform where unsigned int is not 32-bit (or unsigned short not 16-bit), the one: numbers will change accordingly, but the zero: values will still be 1 for 4 (since the MSB is still 0).

John Z

If (and a big if) I understand it, it appears the issue is the 'direction' of the counting

short int example

gcc and ChatGPT
a1 one:14  a1 zero:1
00000000 00000100 count left to right == 14 for 1st 1
00000000 00000100 count right to left ==  1 for 1st 0

Pelle version
a1 one:3  a1 zero:16
00000000 00000100 count right to left ==  3 for ist 1
00000000 00000100 count left to right == 16 for 1st 0

John Z