gpt4 book ai didi

c - 识别位图中设置的位并将其打印在字符串中

转载 作者:行者123 更新时间:2023-11-30 16:50:17 25 4
gpt4 key购买 nike

给定一个无符号 64 位整数。其中设置了多个位。想要处理位图并识别位置并根据位所在的位置返回字符串。示例:无符号整数为 12。表示 1100,这意味着设置了第三位和第四位。这应该打印三四函数接受 unsigned int 并返回字符串。我查看了一些代码,我不认为这是其他问题的重复。

char* unsigned_int_to_string(unsigned long int n)
{
unsigned int count = 0;
while(n)
{
int i, iter;
count += n & 1;
n >>= 1;
}

/*** Need help to fill this block ***/
/** should return string THREE FOUR***/
}


#include <stdio.h>
int main()
{
unsigned long int i = 12;
printf("%s", unsigned_int_to_sring(i));
return 0;
}

最佳答案

您可以通过查找表来暴力破解它,该表包含您感兴趣的每个位的单词表示形式。

char* bit_to_word[10] = { "ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","TEN" }; // and so forth...

然后在函数中检查每一位,如果已设置,则连接 bit_to_word 数组中的相应单词。您可以使用 strcat_s 安全地执行此操作功能。

strcat_s(number_string, BUF_SIZE, bit_to_word[i]);

有一个问题。在第一个单词之后,您还需要添加一个空格,以便您可能想要跟踪它。

此代码检查数字的前 10 位并为测试用例打印出“三四”。但请注意,它不会执行任何内存清理。

#include <stdio.h>
#include <string.h>

#define BUF_SIZE 2048

char* bit_to_word[10] = { "ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","TEN" };

char* unsigned_int_to_string(unsigned long int n)
{
char* number_string = (char*)malloc(BUF_SIZE);
memset(number_string, 0, BUF_SIZE);

int first_word = 1;
unsigned long int tester = 1;
int err;
for (unsigned long int i = 0; i < 10; i++)
{
if (tester & n)
{
if (!first_word)
{
strcat_s(number_string, BUF_SIZE, " ");
}
err = strcat_s(number_string, BUF_SIZE, bit_to_word[i]);
if (err)
{
printf("Something went wrong...\n");
}
first_word = 0;
}
tester <<= 1;
}

return number_string;
}

int main(int argc, char** argv)
{
char* res = unsigned_int_to_string(0b1100);
printf("%s\n", res);
}

关于c - 识别位图中设置的位并将其打印在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42241118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com