从输入中找到连续十六进制数字的最大数量

Find the maximum number of consecutive hex digits from input

本文关键字:十六进制数字 最大数 连续 输入      更新时间:2023-10-16

我在编写一个程序时遇到问题,该程序以十六进制读取 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 timesn", hexDigit, max);
}

我不确定如何实现找出哪个十六进制数字出现最多,因此非常感谢任何关于我可以去的方向的帮助。

我相信

这应该有效:

#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 timesn", answer, max);
}