How to write an algorithm to find the number of bits set in a typical number ?

#include <stdio.h> cbs () { unsigned int v; /* count the number of bits set in v */ unsigned int c; /* c accumulates the total bits set in v */ printf(“Enter v”); scanf(“%u”,&v); for (c = 0; v ; c++) { v = v & (v – 1); /* clear the least significant bit …

How to write a program to connect to a PostgreSQL server ? (program may not be perfect )

#include <stdio.h> #include <stdlib.h> #include <postgresql/libpq-fe.h> int main(int argc, char **argv) { const char *conninfo; const char *serverversion; PGconn *conn; const char *paramtext = “server_version”; conninfo = “hostaddr = 127.0.0.1 dbname = test user = earl password = bigshot”; conn = PQconnectdb(conninfo); if ( PQstatus(conn) != CONNECTION_OK ) { printf(“Unable to establish connection: %s”,PQerrorMessage(conn)); return …

How to write a program to modify a word using a bit mask ?

#include <stdio.h> int main() { typedef int bool; bool f; /* conditional flag */ unsigned int m; /* the bit mask */ unsigned int w; /* the word to modify: if (f) w |= m; else w &= ~m; */ printf(“Enter the word to modify “); scanf(“%u”,&w); printf(“Enter the bit mask “); scanf(“%u”,&m); /* w …

Hacking the program for counting bits set

$gcc counting-bits-set-naive-way-related.c $./a.out Enter v 8474578 Total bits set in v is 11 $./a.out Enter v 1 Total bits set in v is 1 $./a.out Enter v 2 Total bits set in v is 1 $./a.out 3 Enter v a Total bits set in v is 0 $cat counting-bits-set-naive-way-related.c #include <stdio.h> int main() { unsigned …