The initial zero value in whole letters

I am learning (ANSI) C in the C programming language (second edition) .

This is a piece of code from 2.10 Assignment and expression operators :

1 /* bitcount() counts the number of 1-bits in its integer argument */ 2 int bitcount(unsigned x) 3 { 4 int b; 5 for (b = 0; x != 0; x >>= 1) 6 if (x & 01) 7 b++; 8 return b; 9 } 

I'm confused, why is x & 01 written on line 6 and not x & 1 or x & 0x1 ? Is 0 to 1 required?

+6
source share
3 answers

01 can also be written 1 or 0x1.

 01 = Octal Constant Base 8 (1 Decimal) 1 = Decimal Constant. Base 10 0x1 = Hexadecimal Constant. Base 16 (1 Decimal). 

When the book was written, Base 8 (octal) was common in existing computer programming.

+11
source

Leading 0 makes the constant an octal value (base 8).

In this case, it does not differ from 1 or 0x1 , because all of them will have the same binary representation 000...001 . People often use hexadecimal constants to distinguish that a value is used as a bitmask or other bitwise value today. Previously, octal constants were used more often for the same purpose.

 0x1 = hex constant = 1 0X1 = hex constant = 1 01 = octal contant = 1 1 = decimal constant = 1 1U = unsigned decimal constant = 1 
+8
source

Indeed, " 01 " is in principle different from 1 and 0x1 . " 01 " is encoded in octal. Kernighan / Ritchie probably appreciates the ease with which you can convert from octal to binary for this particular problem.

+2
source

Source: https://habr.com/ru/post/969546/


All Articles