簡體   English   中英

如何在C中使用按位將數字轉換為字母數字?

[英]How to convert a number to a alphanumeric using bitwise in C?

我寫了一個程序,將數字轉換為字符串。 核心邏輯使用%10。但是,我正在尋找其他方式。 另一種方法是使用按位運算符。 我想到的第一個問題是如何使用按位運算來分割數字。 我無法考慮這些問題。 這是我通常的程序。

   #include "stdio.h"

void itoaperChar(int n, char *s)
{
    s[0] = '0' + n;

    s[1] = '\0';
}

typedef struct my_string
{
    char val;
    struct my_string *next;
}my_string;

void convertitoString(int nu, char *des)
{
    char tempChar[2];
    my_string *Head = NULL;
    my_string *tempNode = NULL;

    while( nu != 0)
    {
        /** when we apply the logic of traversing from last, the data is accessed as LIFO **/
        /** we are again applying LIFO to make it FIFO **/
        int temp = nu%10;
        itoaperChar(temp,&tempChar);
        if(Head == NULL )
        {
            Head =(my_string*)malloc(sizeof(my_string));

            /**  Remember, strcpy looks for \0 in the source string. Always, ensure that the string is null terminated. Even if the string is just 1 byte.**/
            strcpy(&(Head->val),tempChar);
            Head->next = NULL;
        }
        else
        {
            tempNode = (my_string*)malloc(sizeof(my_string));
            strcpy(&(tempNode->val),tempChar);
            tempNode->next = Head;
            Head = tempNode;
        }

        nu = (nu - temp)/10;

    }

    int lcindex = 0;

    while(Head!=NULL)
    {

        strcpy(&(des[lcindex]),&(Head->val));
        lcindex++;
        tempNode = Head;
        Head=Head->next;
        free(tempNode);
        tempNode = NULL;
    }

    des[lcindex] = '\0';

}

void main()
{
    char t[10];
    convertitoString(1024,t);
    printf("The value of t is %s ", t);
}

由於縮進非常糟糕,因此我不理解您的代碼,但是為什么要使它如此復雜? 使用除以10的數字到字符串程序只能占用幾行(數十行)

如果只想按位操作,可以使用double dabble算法 它僅通過按位運算就可以將數字從二進制轉換為BCD。 從BCD到字符串的轉換只是從壓縮的半字節到2個字符字節的擴展

模數是基於除法的算術運算符; 從根本上說,它是算術運算符,而不是按位運算符。 除非模數是2的冪(在這里不是),否則沒有簡單的方法可以按位運算符實現它。 抱歉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM