2

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
xianyu1337
  • 231
  • 2
  • 7

2 Answers2

1

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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
Yu Hao
  • 119,891
  • 44
  • 235
  • 294