#include<stdio.h>
long long int A = 0xAABBCCDDBBCCFFEE;
long long int B = 0xAACCCCDDBBDDFF00;
int array[8] = {'\0'};
int byte_compare(int A, int B)
{
int i = 0;
long long int j = 0xFF;
long long int C = A;
long long int D = B;
while(i < 8)
{
C = (j & A);
D = (j & B);
printf("C = %x\n",C);
printf("D = %x\n",D);
printf("j = %x\n",j);
if(C == D)
{
array[i] = 1;
}
else
{
array[i] = 0;
}
i++;
j = j << 8;
}
}
main()
{
int i = 0;
byte_compare(A,B);
while(i < 8)
{
printf("array[%d] - %d\n",i, array[i]);
i++;
}
}
long long int A = 0xAABBCCDDBBCCFFEE;
long long int B = 0xAACCCCDDBBDDFF00;
result = 10111010
当A和B字节编号相互匹配时,它应该打印1,否则为0。
对于我的上述程序,它是打印输出
C = ee
D = 0
j = ff
C = ff00
D = ff00
j = ff00
C = cc0000
D = dd0000
j = ff0000
C = bb000000
D = bb000000
j = ff000000
C = 0
D = 0
j = 0
C = 0
D = 0
j = 0
C = 0
D = 0
j = 0
C = 0
D = 0
j = 0
array[0] - 0
array[1] - 1
array[2] - 0
array[3] - 1
array[4] - 1
array[5] - 1
array[6] - 1
array[7] - 1
在前四个字节后无法比较,请帮我说一下我应该使用的数据类型。
答案 0 :(得分:0)
您的代码中存在许多问题
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
void byte_compare(uint64_t C, uint64_t D, int *array)
{
int i = 0;
while (i < 8)
{
printf("C = %"PRIx64"\n" , (C&0xFF));
printf("D = %"PRIx64"\n\n", (D&0xFF));
if ((C&0xFF) == (D&0xFF))
{
array[i] = 1;
}
else
{
array[i] = 0;
}
i++;
C >>= 8;
D >>= 8;
}
}
int main(void)
{
int i = 0;
uint64_t A = UINT64_C(0xAABBCCDDBBCCFFEE);
uint64_t B = UINT64_C(0xAACCCCDDBBDDFF00);
int array[8] = {0};
byte_compare(A, B, array);
while (i < 8)
{
printf("array[%d] - %d\n", i, array[i]);
i++;
}
}
unsigned long long
:位63设置为1,因此将其分配给有符号变量会导致溢出调用UB。使用stdint.h
标准标题,您可以使用更清晰的uint64_t
。byte_compare
函数定义错误,您必须传递具有正确类型的参数:unsigned long long
(uint64_t
)。此外,该函数不返回int,因此应该是void
。printf
格式说明符的%x
需要unsigned int
,而不是uint64_t
。最好的办法是使用inttypes.h
标准头文件中定义的所有格式说明符都很好地报告:在你的情况下PRIx64
是正确的。long long int
来“选择”要检查的字节。这是完全错误的,因为最后一次转换导致signed
值溢出UB与第1点相同。stdint.h
还有一些宏,它们将正确的后缀附加到文字。使用面具的另一个例子:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
void byte_compare(uint64_t C, uint64_t D, int *array)
{
uint64_t mask = UINT64_C(0xFF00000000000000);
while (mask > 0)
{
printf("C = %"PRIx64"\n" , (C&mask));
printf("D = %"PRIx64"\n\n", (D&mask));
if ((C&mask) == (D&mask))
{
*array = 1;
}
else
{
*array = 0;
}
mask >>= 8;
array--;
}
}
int main(void)
{
int i = 0;
uint64_t A = UINT64_C(0xAABBCCDDBBCCFFEE);
uint64_t B = UINT64_C(0xAACCCCDDBBDDFF00);
int array[8] = {0};
byte_compare(A, B, &array[7]);
while (i < 8)
{
printf("array[%d] - %d\n", i, array[i]);
i++;
}
}