2017-02-15 138 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); 
}