我必须读取近 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/