C言語

FNVハッシュ関数

FNVハッシュ関数は簡単に実装できるハッシュ関数です。 Twitterで見かけたので忘れないうちにメモ。 FNV-1 hash hash=offset_basis for each octet_of_data to be hashed hash=hash*FNV_prime hash=hash xor octet_of_data return hash octet_of_dataは変換…

日付時刻(2)

asctime_r()、ctime_r()、gmtime_r()、localtime_r() char *asctime_r(const struct tm *tm,char *buf); char *ctime_r(const time_t *timep,char *buf); struct tm *gmtime_r(const time_t *timep,struct tm *result); struct tm *localtime_r(const time_t…

日付時刻(1)

asctime()、ctime()、gmtime()、localtime()、mktime()、timegm() 標準のCで使える関数ですが、知らない人が多いと思うので紹介しておきます。 #include <time.h> struct tm { int tm_sec; /* 秒 */ int tm_min; /* 分 */ int tm_hour; /* 時間 */ int tm_mday; /* </time.h>…

スリープ

プログラムの実行を一時的に休止する関数として、sleep()、usleep()、nanosleep()があります。 sleep()は秒単位、usleep()はマイクロ秒(100万分の1秒)単位、nanosleep()はナノ秒(10億分の1秒)単位で休止できます。 sleep() #include <unistd.h> unsigned int sleep(uns</unistd.h>…

すかすかの配列から効率良く全要素を取り出す

一番右端に立っているビットの位置を求めるアルゴリズムが載っていました。http://d.hatena.ne.jp/siokoshou/20090704#p1 http://chessprogramming.wikispaces.com/BitScan#DeBruijnMultiplationまさしく黒魔術!良くこんなの思いつくなぁ、と感心する事しき…

自動拡張する文字列用バッファ

GString #include <glib.h> typedef struct { gchar *str; gsize len; gsize allocated_len; } GString; GString* g_string_new(const gchar *init); GString* g_string_append(GString *string, const gchar *val); GString* g_string_prepend(GString *string, con</glib.h>…

ガーベージコレクタ

メモリリークの問題に悩まされている人は多いと思います。ガーベージコレクタを使うと、メモリ管理の煩わしさから解放されます。 Boehm GC #include <gc/gc.h> void GC_INIT(void); void *GC_MALLOC(size_t size); void *GC_MALLOC_ATOMIC(size_t size); void *GC_REA</gc/gc.h>…

DNS

djbdns #include <djbdns/dns.h> void dns_random_init(const char seed[128]); int dns_ip4(stralloc *out, const stralloc *fqdn); int dns_name4(stralloc *out, const char ip[4]); int dns_mx(stralloc *out, const stralloc *fqdn); djbdnsに含まれているライブラリ</djbdns/dns.h>…

自動拡張する配列

GLibには自動拡張する配列があります。要素の追加、削除が容易に行えます。 GArray #include <glib.h> typedef struct { gchar *data; guint len; } GArray; GArray* g_array_new(gboolean zero_terminated, gboolean clear_, guint element_size); #define g_array_</glib.h>…

ハッシュテーブル

glibcのハッシュテーブル #include <search.h> int hcreate(size_t nel); ENTRY *hsearch(ENTRY item, ACTION action); void hdestroy(void);nelでハッシュテーブルに格納できるデータ数の最大値を設定します。 キーには文字列しか使えません。 hdestroy()を呼ぶとハッ</search.h>…

一行入力

getline()、getdelim() #define _GNU_SOURCE #include <stdio.h> ssize_t getline(char **lineptr, size_t *n, FILE *stream); ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);Linuxで使える関数です。 getlineはstreamから一行読み込み、*li</stdio.h>…