C - 位矩阵的位域

问题描述 投票:0回答:1

我必须读取几乎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比特。

问候

c matrix bit bit-fields
1个回答
0
投票

因为我将拥有二进制字符串,所以我只想对矩阵上的每个元素使用一个位而不是字节。我刚刚发现了比特字段,但我不明白如何使用它来使代码#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.