我在编写一个以十六进制读取64位无符号长整数的程序时遇到问题,找到最频繁的十六进制数字,并返回它出现的次数以及数字本身。 例, 输入:0xABCD_FFFF_43FF_42CF 输出:十六进制数字F出现4次
到目前为止,这是我的代码:
#include <stdio.h>
int main()
{
int i = 0;
char count = 0;
char max = 0;
char hexDigit = 0;
unsigned long long x = 0xABCDFFFF43FF42CF;
for ( i = 0; i < 16; i++)
{
if (( x >> i ) & 0xF) // checking bits to see if they match previous hex digit
{
count++; // count increases if they are the same
}
else
{
count = 0;
}
if (count > max)
{
max = count;
}
}
printf("Hex digit %x occured %d times\n", hexDigit, max);
}
我不确定如何实现找出哪个十六进制数最多,所以任何有关我可以去的方向的帮助都非常感谢。
答案 0 :(得分:0)
我相信这应该有效:
#include <stdio.h>
int main()
{
int i = 0;
char count = 0;
char max = 0;
char hexDigit = -1;
char answer;
unsigned long long x = 0xABCDFFFF43FF42CF;
for ( i = 0; i < 16; i++)
{
char curr = (x>>(4*i)) & 0xF;
if (curr==hexDigit) // checking bits to see if they match previous hex digit
{
count++; // count increases if they are the same
}
else
{
count = 1;
hexDigit = curr;
}
if (count > max)
{
max = count;
answer=hexDigit;
}
}
printf("Hex digit %x occured %d times\n", answer, max);
}