2012-02-12 241 views
2

我想获得无符号long long的二进制形式,并将它的每一位存储在一个数组中。无符号long long的二进制表示

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

0000000000000000 0000000000000000 
FFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFF 
3000000000000000 1000000000000001 

其中每个条目是十六进制表示的64位整数。我使用一个无符号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 

任何人都可以看到我犯了一个错误?

编辑

我同时获得阅读和打印反转后的正确的输出,但我的问题是我需要的数组首先最显著字节,所以我可以操纵它。任何想法如何可以做到?我是否需要将它重新分配给一个新的数组并将它们反向复制?

+0

使用'B [I]'而不是'*(B + I)',它更清晰。 – Borealid 2012-02-12 06:49:29

+0

有两个问题: - 什么是最低位的位数? - 打印位时,最低位应该先打印(左边)还是最后(左边)? – 2012-02-12 06:56:16

+0

@DaleHagglund十六进制值是从一个人创建的文件读入的,所以它们应该都是大端的。 – 2012-02-12 15:27:19

回答

5

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

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

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

对于第二个数字:

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

对应于你的第一个第一个字节,0x10

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

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

[示例](http://ideone.com/QiS99) – jfs 2012-02-12 07:52:49

+0

谢谢,那正是我的问题。 – 2012-02-12 15:39:44

+0

对于我的程序来说,我需要首先获得最重要字节的二进制表示。任何想法我怎么能做到这一点?我使用当前输出重新编辑上面的内容。 – 2012-02-12 16:12:01