簡體   English   中英

C-位矩陣的位字段

[英]C - Bit Fields for bit Matrix

我必須讀取幾乎1M的具有相同長度的0和1(即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位。

Saludos

由於我將使用二進制字符串,因此我只希望對矩陣中的每個元素使用一個位,而不是一個字節。 我剛剛發現了位域,但是我不知道如何使用它來使代碼1使用100位。

位字段不適合此操作,因為它們無法索引。

我們可以為每個元素使用一位,但隨后無法通過寫入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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM