c - 通过串联将位(字节)存储在 long long 中

标签 c arrays byte concatenation long-integer

poly8_bitslice() 数组如果char 作为输入,该输入将通过函数intToBits() 转换为位(字节)。

转换后,我想将结果存储在 long long 变量中。这可能吗? 我可以连接 intToBits() 的结果吗?

我想用以下代码来做到这一点:

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <string.h>
//#include <math.h>

typedef unsigned char poly8;
typedef unsigned long long poly8x64[8];

void intToBits(unsigned k, poly8 nk[8]) {
    int i; 
    for(i=7;i>=0;i--){        
        nk[i] = (k%2);        
        k = (int)(k/2);
    }
}

void poly8_bitslice(poly8x64 r, const poly8 x[64])
{
  //TODO
    int i;
    for(i=0;i<64;i++){
        poly8 xb[8];
        intToBits(x[i], xb);
        int j;
        long long row;
        for(j=0;j<8;j++){
            row = row + x[j];
        }

        printf("row=%d \n", row);         
    }
}

int main()
{

  poly8 a[64], b[64], r[64];
  poly8x64 va, vb, vt;
  int i;

  FILE *urandom = fopen("/dev/urandom","r");
  for(i=0;i<64;i++)
  {
    a[i] = fgetc(urandom);
    b[i] = fgetc(urandom);
  }

  poly8_bitslice(va, a);
  poly8_bitslice(vb, b);

  fclose(urandom);
  return 0;
}

最佳答案

我不确定我完全理解你的问题,但你可以这样做

char ch0 = 0xAA;
char ch1 = 0xBB;
char ch2 = 0xCC;
char ch3 = 0xDD;
long long int x = 0;           // x is 0x00000000
x = (long long int)ch0;        // x is 0x000000AA
x = x << 8;                    // x is 0x0000AA00
x = x | (long long int)ch1;    // x is 0x0000AABB
x = x << 8;                    // x is 0x00AABB00
x = x | (long long int)ch2;    // x is 0x00AABBCC
x = x << 8;                    // x is 0xAABBCC00
x = x | (long long int)ch3;    // x is 0xAABBCCDD

在这种情况下,x 将包含 0xAABBCCDD

<<运算符会将左侧运算符的内容移动右侧运算符指定的数字。所以0xAA << 8将变成0xAA00 。请注意,它会在移位时在末尾附加零。 |运算符将对其两个操作数执行按位或操作。那就是一点一点或者。因此,左侧运算符的第一位将与右侧运算符的第一位进行“或”运算,结果将放置在结果的第一位中。 任何结果为零的事物都如此

0xAA00 | 0x00BB

会导致

0xAABB

一般来说,有点附加功能是

long long int bitAppend(long long int x, char ch) {
    return ((x << 8) | (long long int)ch);
}

此函数将采用您需要附加的 long long 整数和要附加到它的 char ,并返回附加的 long long int 。请注意,一旦 64 位填满,高位将被移出。

例如

long long int x = 0x1122334455667788
x = x << 8;    // x now is 0x2233445566778800

这将导致 x 为 0x2233445566778800因为 long long int 中只有 64 位,所以高位必须移出。

关于c - 通过串联将位(字节)存储在 long long 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42886766/

相关文章:

c++ - 如何操作字符数组

c - Linux 上的 OpenGL : dlopen libGL. 所以

java - 如何比较包含字符串的对象?

arrays - 如何在不使用 for 循环的情况下引用列索引向量更改矩阵的元素?

java - 生成特定长度范围内唯一的字符串

Swift:字节数组到十进制值

指针数组和二维数组可以视为相同吗

c - 从文件选择器中获取文件名

c - MD5——添加消息长度

java - 重复文件的功能与原始文件不同