C

square root

/* square root function with fixed boundary */
#include <math.h>
static const float boundary = 0.01;

float sqroot(float x) {
  float r = 1.0;
  do {
      r = (r + x / r) / 2;
  } while (fabs(r * r - x) > boundary);
  return r;
}

C is simply the system programming language -- basically available everywhere and providing only a very thin layer above your hardware.

open source software

I contributed significantly to these projects:

preprocessor fun

#define CONCAT(x,y)    x "" y
#define STRING(z)      #z
#define COMBINE(a,b)  CONCAT( STRING(a), STRING(b) )

you can then use these defines like this:

#define PREFIX     /usr/local
#define PIDFILE    COMBINE( PREFIX, /var/run/daemon.pid )
FILE *file = fopen(PIDFILE, "w+");

...and a little snippet to get the return value of a UNIX process:

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
  printf("%d", system(argv[1]) >> 8);
}

potpourri

change user -- for dropping privileges when started as root

#include <pwd.h>
#include <unistd.h>

int drop_privileges(char *user) {
        struct passwd *runas_pw;
        uid_t user_id;
        gid_t group_id;

        runas_pw = getpwnam(user);
        if (NULL == runas_pw) {
                return -1;
        }

        user_id = runas_pw->pw_uid;
        group_id = runas_pw->pw_gid;

        if (0 != setgid(group_id)) {
                return -2;
        }
        if (0 != setuid(user_id)) {
                return -3;
        }

        return 0;
}
</pre>

test endianess at run-time

#include <stdboolh.h>
#include <stdint.h>

bool isbigendian() {
    union {
        uint16_t i16;
        uint8_t i8[2];
    } u;
    u.i16 = (uint16_t)0x4321;

    /* ckeck contents of lower byte for most significant byte value */
    if ((uint8_t)0x43 == u.i8[0]) {
        return true;
    } else {
        return false;
    }
}

print signed 8 bit integer as binary (for your CS homework); can easily be transformed in versions for other integer sizes

#include <stdint.h>
#include <stdio.h>

void bprint8(int8_t n) {
    uint8_t b;
    for (b = 1 << 7; b > 0; b >>= 1)
        printf("%d", b & n ? 1 : 0);
}