【问题标题】:C - Bit Fields for bit MatrixC - 位矩阵的位域
【发布时间】:2016-12-04 22:22:49
【问题描述】:

我必须读取几乎 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 的 char 矩阵:100bytes。 由于我将使用二进制字符串,因此我只想对矩阵上的每个元素使用一点而不是字节。我刚刚发现了位域,但我不知道如何使用它来使代码#1 使用 100 位。

感谢

【问题讨论】:

  • calloc 不需要演员表 - 这很糟糕 - 请参阅 stackoverflow.com/questions/605845/…
  • 嗯,我不知道有那么糟糕。
  • sizeof(char) 定义为 1。
  • 1 字节,我正在寻找是否可以使用 1bit

标签: c matrix bit bit-fields


【解决方案1】:

由于我将使用二进制字符串,因此我只想为每个字符串使用一点 矩阵上的元素而不是字节。我刚刚发现了位域 但我不知道如何使用它来使代码#1 使用 100 位。

位域不适合这个,因为它们不能被索引。

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

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多