我正在從具有「000101」或「100010」等數據的文本文件讀取代碼(二進制)。然後我將這些二進制字符串進一步串聯起來。我無法使用前導零,我不能跳過。我一直試圖通過首先將二進制字符串轉換爲int(使用atoi())然後轉換爲十六進制字符串來實現。但是如果我使用該函數,則前導零將截斷前導零。我在這裏搜索過,但給出的解決方案不是用C語言編寫的。有沒有直接的方法來做到這一點,否則我將不得不跟蹤一切?提前致謝。 這裏是我的函數,它接受INT作爲輸入,然後將其轉換爲十六進制字符串將帶前導零的二進制字符串轉換爲十六進制字符串
void toHex(int n, char str[]) /* Function to convert binary to hexadecimal. */
{
int i=0,decimal=0, rem;
char temp[2];
while (n!=0)
{
decimal += (n%10)*pow(2,i);
n/=10;
++i;
}
/* At this point, variable decimal contains binary number in decimal format. */
i=0;
while (decimal!=0)
{
rem=decimal%16;
switch(rem)
{
case 10:
str[i]='A';
break;
case 11:
str[i]='B';
break;
case 12:
str[i]='C';
break;
case 13:
str[i]='D';
break;
case 14:
str[i]='E';
break;
case 15:
str[i]='F';
break;
default:
str[i]=rem+'0';
break;
}
++i;
decimal/=16;
}
str[i]='\0';
strrev(str); // Function to reverse string.
if(strlen(str)==1)
{
temp[0] = '0';
temp[1] = str[0];
temp[2] = '\0';
strcpy(str,temp);
}
else if(strlen(str)==0)
{
temp[0] = '0';
temp[1] = '0';
temp[2] = '\0';
strcpy(str,temp);
}
}
爲什麼前導零是一個問題?你期望有不同的產出嗎? – usr2564301 2014-11-02 13:14:16
我希望調用strrev()來反轉字符串,而不會丟失字符串終止符。因此,可以使用完整的字符串。因此,檢查是否需要strlen(str)== 1和strlen(str)== 0。 – user3629249 2014-11-02 21:58:55
參數'n'是一個數字,例如(10)將表示爲0x0000000a。所以第一個循環會導致0x0000000a作爲變量decimal中的值。 I.E.第一個循環沒有效果。 – user3629249 2014-11-02 22:04:19