clinuxsizeofbitcount

How can I know the bit count of a cpu/os in C


I know how to get the bit count of a cpu or an operation system with shell.

cat /proc/cpuinfo | grep lm #-> get bit count of a cpu
uname -a                    #-> get bit count of an operation system

However, how can we get the bit count of those in a C program. This is an interview question and my solution is as follow:

int *ptr;
printf("%d\n", sizeof(ptr)*8);

But the interviewer said that was wrong. So, what is the correct answer?


Solution

  • POSIX provides a C function uname as well. You can get similar result like the shell command uname:

    #include <stdio.h>
    #include <sys/utsname.h>
    
    int main(){
        struct utsname buf;
        uname(&buf);
        printf("sysname: %s\nversion: %s\nmachine: %s\n ", buf.sysname, buf.version, buf.machine);
        return 0;
    }
    

    Output on my machine:

    sysname: Linux
    version: #1 SMP Tue Oct 2 22:01:37 EDT 2012
    machine: i686