C语言中的位图是什么? [英] What is a bitmap in C?

查看:331
本文介绍了C语言中的位图是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

位图是位数组.如何在C中实现?

A bitmap is an array of bits. How is it implemented in C?

推荐答案

我假设您正在问如何在C中实现一个位图(或位数组).令人惊讶的是,

I assume you're asking how to implement a bit map (or bit array) in C. Surprisingly, the Bit_array entry on wikipedia describes the concept, but doesn't actually show how to to implement the fundamental operations, so here goes.

简而言之,创建一个您喜欢的无符号类型的数组,然后进行正确的算术,以确定如何设置/清除其中的一些位.

In short, make an array of your favorite unsigned type, and do the right arithmetic to decide how to set/clear a bit in it.

#include <limits.h>    /* for CHAR_BIT */
#include <stdint.h>   /* for uint32_t */

typedef uint32_t word_t;
enum { BITS_PER_WORD = sizeof(word_t) * CHAR_BIT };
#define WORD_OFFSET(b) ((b) / BITS_PER_WORD)
#define BIT_OFFSET(b)  ((b) % BITS_PER_WORD)

void set_bit(word_t *words, int n) { 
    words[WORD_OFFSET(n)] |= (1 << BIT_OFFSET(n));
}

void clear_bit(word_t *words, int n) {
    words[WORD_OFFSET(n)] &= ~(1 << BIT_OFFSET(n)); 
}

int get_bit(word_t *words, int n) {
    word_t bit = words[WORD_OFFSET(n)] & (1 << BIT_OFFSET(n));
    return bit != 0; 
}

这篇关于C语言中的位图是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆