nsg
nsg

Reputation: 10590

Why are decimal numbers used in bitmasks?

This is a pretty basic question, and I'm sure that there's an easy answer to it, but I don't know the search term I should be using to look for an answer. Here it goes:

I'm trying to understand how bitmasks work. On Linux systems there's:

struct stat

that has a st_mode member that's used to determine whether the file being inspected is a regular file, a directory, a symbolic link, and others. So, it's possible to write a simple function that you can pass a name to and get whether or not the name represents a directory:

16 int isadir( char *name )
17 /*
18  *      calls stat, then masks the st_mode word to obtain the
19  *      filetype portion and sees if that bit pattern is the
20  *      pattern for a directory
21  */
22 {
23         struct stat info;
24 
25         return ( stat(name,&info)!=-1 && (info.st_mode & S_IFMT) == S_IFDIR );
26 }

When I look at the bitmask, I see it's represented as follows:

/* Encoding of the file mode.  */

#define __S_IFMT        0170000 /* These bits determine file type.  */

I thought bitmasks could only have 0s and 1s. Why is there a 7 in the mask?

Upvotes: 0

Views: 1626

Answers (2)

Déjà vu
Déjà vu

Reputation: 28850

A byte is 8 bits, and can be expressed in decimal (0 to 255), octal (000 to 377), hexadecimal (00 to FF) or binary (00000000 to 11111111). Let's number the bits, from bit 0 to bit 7:

76543210

Actually a number may be expressed in any base, but mainly octal and hexadecimal are convenient when one want to break down the number into bits ; expressing a byte in octal is easier as

 z  y  x
76543210

x is bits 0 to 2, y is bits 3 to 5 and z is bits 6 and 7.

Thus in your exemple, 017 octal number is

 0   1   7
00 001 111

Numbers expressed in octal base (8-base) are easier to be converted to binary. (in hexa that would be 0F).

In C (...), octal literal numbers start with a leading zero (0...), and in hexadecimal they start with leading 0x (0x...). As it is easier to visualize bits of numbers expressed in octal,

022 & 017

gives in binary

"00 010 010" &
"00 001 111"

result can be found out easily

"00 000 010"

In decimal, that would be 18 & 15.

Upvotes: 3

mvp
mvp

Reputation: 116417

Numbers starting with a leading 0 are octal numbers — this is standard C syntax.

And these can be useful for bitmasks, especially to represent Unix permissions.

Upvotes: 4

Related Questions