2017-02-15 136 views
0

中给出无符号的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; 
} 
+0

为什么你定义函数返回'char *',而你实际返回的是'unsigned int'? – Matso

+0

马索,确定位集的数量,它们的位置和从它们派生的字符串。我试过的粘贴代码。 –

回答

0

无需编写实际的代码,这里是一个基于字符串的64元的查找表的简单算法的描述。 0 = ZERO,1 = 1,2 = 2 ... 63 = 63。这个表格将是一个64个元素的字符串数组。对于C,你可以使用char [256]握住你的琴弦使静态二维数组(或使用最大字符串+ 1的值优化),或者你可以做一个动态使用malloc在for循环)

然后你定义你的输出字符串。

然后,您编写一个For循环,使用位掩码遍历所有位(使用左移位),如果设置了位,则可以将输出字符串(使用strcat)与空格和查找表的内容连接起来对于那个位置。

下面是你将如何进行串联的简短代码片段:(确保输出字符串在outputstring变量中有足够的内存来容纳最大字符串如果你想更复杂并优化内存使用,你可以使用malloc和realloc,但你必须处理释放内存时不再需要它。

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

int main() 
{ 
    char str[80]; 
    strcpy (str,"these "); 
    strcat (str,"strings "); 
    strcat (str,"are "); 
    strcat (str,"concatenated."); 
    puts (str); 
    return 0; 

}

在你的情况,3位将遇到的第一个设置位和输出字符串将包含“THREE”,那么在下一次迭代时,位4将被检测为设置并且输出将被追加作为“三四”。

注:由于这似乎是一个学术问题,我想指出的是,这里存在着复杂的经典案例VS空间权衡。我上面的描述是以牺牲空间为代价的最小复杂性。意思是说,在这些字符串中有很多字符串会有64个冗余字符串。例如:二十二,三十二,四十二,五十二和六十二,都包含字符串“TWO”。空间可以通过使用一半字符串来优化:零,一,通过NINETEEN,然后二十,三十,四十,五十,六十。但是,对于大于TWENTY的位,您的索引逻辑将更加复杂。对于第21位,您需要连接TWENTY和ONE。

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); 
}