リアルに引越したわけではなく,Webサーバの話です.(笑
実は先週からwww.sabamiso.netのIPアドレスが変っています.
おそらくほとんどの方には新しいDNSの設定が伝搬していると思いますが, 念のために旧サーバも来週まで同時に稼動させています.
ぱっと思いつく方法は,
unsigned int n = 0xffffffff;
unsigned int total = 0;
total += ( n >> 0 ) & 0x0001;
total += ( n >> 1 ) & 0x0001;
・
・
・
total += ( n >> 31 ) & 0x0001;
printf("total=%d\n",total);
ですが,これだと芸がないので変な方法で解答.
/**
* 32bit変数の1であるビットが
* 何個あるか数えるプログラム(Java版)
*/
public class BitCount {
private static int total = 0;
private static void count(byte buf[], int p) {
total += buf[p] - '0';
count(buf, p + 1);
}
public static void main(String args[]) {
int n = 0xffffffff;
byte buf[] = Integer.toBinaryString(n).getBytes();
try{ count(buf, 0); } catch (ArrayIndexOutOfBoundsException e) {}
System.out.println("total=" + total);
}
}
例外をつかっちゃダメとは書いてないし...(笑
休日出勤中の息抜きでした...