C File Permission Conversion

I'm new to C, and I'm attempting to write a script similar to the stat command for practice. I only had a problem converting st_mode to an octal permission format. I remembered I had littleutils installed which contains a script called filemode, so I checked the source and it yielded something like :

%04o, file_stats.st_mode & 4095

Now I'd just like to understand that bit of code. Any help is appreciated.

& by itself like that is a bitwise and, and 4095 is one away from being 4096, a nice round binary number. In binary, 4095 looks like:

0000111111111111

All the higher-order bits, where 4095 is zero, get turned off, only the lower-order bits get let through.

C supports octal directly, though. Numbers beginning with a 0 are assumed to be octal. The value of 0777 is the same as that of 777 in the chmod sense, and you can get the same value as 4095 with the less-inexplicable octal value of 07777.

Hrm, I'm not quite sure I understand. If I just put the value returned from st_mode(33152)through like this:

%04o\n", statbuf.st_mode

I get 100600. If it's not too much trouble could you break down the code?

See Unix File Permissions...at least the beginning where I show how the mode is stored.

Your value of 100600 is two pieces of data. The last 4 digits tell you that the file has the same permissions as could be achieved via "chmod 600 file". So you need to isolate those 4 digits and throw away that leading 10. That is what the code is doing.

Thank you for the replies. I believe I've got it now.