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

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

问题描述

位图是一个位数组.它是如何在 C 中实现的?

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

推荐答案

我假设您在问如何在 C 中实现位图(或位数组).令人惊讶的是,Bit_array 维基百科条目描述了这个概念,但实际上并没有展示如何实现基本操作,所以在这里去.

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天全站免登陆