Question

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?

Was it helpful?

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

OTHER TIPS

On Linux, a simple way is to do e.g. popen with the uname -m command and parse the output.

Another way is to look at the source for the uname command (as it's readily available) and implement something based on that directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top