C - 位矩阵的位字段

标签 c matrix bit bit-fields

我必须读取近 1M 相同长度的包含 1 和 0 的字符串(即 01111010),并比较它们在 C 上的汉明距离。

我的想法是做这样的事情: 代码#1

typedef struct _matrix
{
    unsigned int n_rows;
    unsigned int n_cols;
    char ** mat;
} matrix;

matrix *create_matrix(matrix *mtrx)
{
    //char** mat;
    //matrix* mtrx = malloc(sizeof(matrix));
    int x=10, y=10, i;
    mtrx->mat = calloc(x+1, sizeof(char*));
    for(i = 0;i<y;i++) mtrx->mat[i] = calloc(y+1, sizeof(char));
    mtrx->n_rows = x;
    mtrx->n_cols = y;
    return mtrx;
}

int main()
{
    matrix* mtrx = malloc(sizeof(matrix));
    mtrx = create_matrix(mtrx);
    int i;
    for(i=mtrx->n_rows;i>=0;i--) free(mtrx->mat[i]);
    free(mtrx->mat);
    free(mtrx);

    return 0;
}

这将创建一个 10x10 字符矩阵:100 字节。 由于我将拥有二进制字符串,因此我只想对矩阵上的每个元素使用一位而不是一个字节。我刚刚发现了有关位字段的信息,但我不知道如何使用它来使 code#1 使用 100 位。

致敬

最佳答案

Since I'll have binary strings I want to use only a bit for each element on the matrix instead of a byte. I just found about bit-fields but I'm don't understand sure how to use it to make code#1 use 100bits.

位字段不适合这种情况,因为它们无法索引。

我们可以为每个元素使用一位,但是我们无法通过编写mat[i][j]来访问;我们宁愿使用 getter 和 setter 宏或函数,例如。例如:

typedef struct _matrix
{
    unsigned int n_rows;
    unsigned int n_cols;
    unsigned char *mat;
} matrix;

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

matrix *create_matrix(matrix *mtrx)
{
    int x=10, y=10;
    mtrx->mat = calloc((x*y+CHAR_BIT-1)/CHAR_BIT, 1);   // one bit per element
    mtrx->n_rows = x;
    mtrx->n_cols = y;
    return mtrx;
}

inline _Bool get_matrix(matrix *mtrx, unsigned row, unsigned col)
{
    unsigned idx = row*mtrx->n_cols+col;
    unsigned byt = idx/CHAR_BIT;
    unsigned bit = idx%CHAR_BIT;
    return mtrx->mat[byt]>>bit&1;
}

inline void set_matrix(matrix *mtrx, unsigned row, unsigned col, _Bool val)
{
    unsigned idx = row*mtrx->n_cols+col;
    unsigned byt = idx/CHAR_BIT;
    unsigned bit = idx%CHAR_BIT;
    mtrx->mat[byt] = mtrx->mat[byt]&~(1<<bit)|val<<bit;
}

print_matrix(matrix *mtrx)
{
    int i, j;
    for (i=0; i<mtrx->n_rows; ++i, puts(""))
    for (j=0; j<mtrx->n_cols; ++j) printf("%d", get_matrix(mtrx, i, j));
}

int main()
{
    matrix mtrx;
    create_matrix(&mtrx);
    set_matrix(&mtrx, 0, 0, 1);
    set_matrix(&mtrx, 9, 9, 1);
    print_matrix(&mtrx);
    free(mtrx.mat);
    return 0;
}

关于C - 位矩阵的位字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40964409/

相关文章:

c++ - 如何计算非方(矩形)矩阵的正交基

c - 内存中的位存储顺序

c++ - 我们的程序可以在编译时确定它正在被哪个编译器编译吗?

python - 对 numpy 数组有多个相等条件

c - C 中 int 文字之间的零

c++ - 从文件 [C++] 中读取矩阵数据及其维度

ruby - 使用 Ruby 压缩位串

java - 在Java中读取32位无符号整数中的位值

c - 使文字和线条出现在 GTK 窗口上...使用 XLIB 和 GDK

c - 为什么这个程序会自动将结果转换为 INT_MIN 而不是整数溢出?