c - unsigned long long 的二进制表示

标签 c

我试图获取 unsigned long long 的二进制形式并将其每一位存储在数组中。

我有一个像这样的输入文件:

0000000000000000    0000000000000000
FFFFFFFFFFFFFFFF    FFFFFFFFFFFFFFFF
3000000000000000    1000000000000001

其中每个条目都是以十六进制表示的 64 位整数。我使用 unsigned long long 来保存该值,然后迭代这些位并尝试将它们存储在数组中,但某些数组的位位置错误。

这是我所拥有的:

char key_in[17];
char plaintext_in[17];

//64-bit long variables to hold the 64-bit hex values in the input file
unsigned long long key, plaintext;

//I read an entry from the file with fscanf
fscanf(infile,"%s %s",&key_in, &plaintext_in)

//convert the numbers from hex to unsigned long long with strtoull
key = strtoull(key_in, NULL, 16);
plaintext = strtoull(plaintext_in, NULL, 16);

//initialize arrays with 64 positions that will hold the 
//binary representation of the key and plaintext
int key_arr[64];
int pt_arr[64];

//fill the arrays with the binary representations
//of the plaintext and the key
int64_to_bin_array(key, key_arr, 64);
int64_to_bin_array(plaintext, pt_arr, 64);    

//print both arrays
printArray(key_arr, 64);
printArray(pt_arr,  64);

这是我创建的函数int64_to_bin_arrayprintArray:

/* Converts from an unsigned long long into an array of 
integers that form the binary representation of a */
void int64_to_bin_array(unsigned long long a, int *b, int length)
{
   int i;
   for(i = 0; i < length; i++)
   {
      *(b+i) = (a >> i) & 1; //store the ith bit in b[i]
   }
}

/* prints a one-dimensional array given
   a pointer to it, and its length */
void printArray(int *arr, int length)
{
   int i;
   for(i = 0; i < length; i++)
   {
      printf("%d ", *(arr + i));
   }
   printf("\n\n");
}   

但是,当我打印第三个输入的数组时,我收到了错误的结果:

输入(十六进制):

1.  3000000000000000    2.  1000000000000001   

输出(二进制):

1    00000000 00000000 00000000 00000000 00000000 00000000 00000000 00001100 

2    10000000 00000000 00000000 00000000 00000000 00000000 00000000 00001000

谁能看出我哪里出错了?

编辑

在反向读取和打印后,我得到了正确的输出,但我的问题是我需要数组首先具有其最重要的字节,以便我可以操作它。有什么想法可以做到吗?我是否必须将其重新分配给一个新数组并反向复制元素?

最佳答案

尝试以相反的方式阅读它。让我们看最后一个八位字节:

00001100 = 0x0C
00110000 = 0x30 <---

这对应于您的第一个八位字节,0x30

对于第二个数字:

00001000 = 0x08
00010000 = 0x10 <---

这对应于您的第一个八位字节,0x10

如果你像这样打印它,你可能会得到你所期望的结果:

for(i = length - 1; i >= 0; i--)

关于c - unsigned long long 的二进制表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9246980/

相关文章:

c - 信号处理程序和 waitpid 共存

c - 删除函数无法删除链表中除第一个节点之外的节点

c - fscanf 是否分配内存并在字符串末尾放置一个 NUL 字节?

c - 将库中的专用 ELF 部分合并到应用程序专用 ELF 部分

c - 用 LD_PRELOAD 覆盖 execve() 有时只有效

c - 哈希表搜索,命令提示奇怪的错误

c - 使用给定数组在 C 中反转数组

c - 为什么我们使用零长度数组而不是指针?

C - fgets 在初始化指针时不等待输入

c - C99 fesetround()/fegetround() 状态是按线程还是按进程?