2016-08-16 100 views
0

我想encode_char_inç用來取代奇數位指數之間甚至指數位,這樣我怎麼能做出符號的字符像無符號

'W' = 57h = 0101_0111 
     ABh = 1010_1011 

因爲char在C C函數可能成爲負數,我不能在位之間切換(僅在signed char - 它的工作原理)。 它在下面的代碼中給了我另一個值 。

#include <stdio.h> 
#include <limits.h> 
#define TRUE 1 
#define ONE 1 

char codeBinPair(char str); 

void main() 
{ 
char str[2] = { 182,NULL }; 
unsigned char ch = 'W'; 
printf("ch = %x\n", ch); 
ch = codeBinPair(ch); 
printf("ch = %x\n", ch); 
ch = codeBinPair(ch); 
printf("ch = %x\n", ch); 
} 

char codeBinPair(char str) 
{ 
    int idx = 0; 
    char ch1 = str, ch2 = 0, mask = ONE; 
    while (TRUE) 
    { 
    mask <<= ONE; 
    mask &= ch1; 
    mask >>= ONE; 
    ch2 |= mask; 
    // Initialize the mask 
    mask = ONE; 
    mask <<= idx; 
    mask &= ch1; 
    mask <<= ONE; 
    ch2 |= mask; 
    // Index next loop we want to replace 
    idx += 2; 
    // If We Finish whole Byte 
    if (idx == CHAR_BIT) 
     return ch2; 
    // Initialize the mask 
    mask = ONE;  
    mask <<= idx; 
} 
} 
+1

C已簽署'和char''無符號char',你知道的。如果你在乎做點數學,那就用其中之一。 (或者,甚至更好的是,'int_least8_t'和'uint_least8_t'。) – cHao

+0

@cHao他似乎知道,因爲他宣稱'unsigned char ch ='W''。所以代碼只需要使用'unsigned char'作爲'codeBinPair'參數的類型。 – Barmar

+0

'void main()'是一個無效簽名,並調用未定義的行爲。那麼不要定義你自己的boolen常量/類型,而是使用標準的!最後,你的代碼可能會調用未定義的行爲,或者依賴於某些移位和某些值的實現定義的行爲。 – Olaf

回答

0

改變所有的charcodeBinPairunsigned char

unsigned char codeBinPair(unsigned char str) 
{ 
    int idx = 0; 
    unsigned char ch1 = str, ch2 = 0, mask = ONE; 
    while (TRUE) 
     { 
      mask <<= ONE; 
      mask &= ch1; 
      mask >>= ONE; 
      ch2 |= mask; 
      // Initialize the mask 
      mask = ONE; 
      mask <<= idx; 
      mask &= ch1; 
      mask <<= ONE; 
      ch2 |= mask; 
      // Index next loop we want to replace 
      idx += 2; 
      // If we finish whole byte 
      if (idx == CHAR_BIT) 
       return ch2; 
      // Initialize the mask 
      mask = ONE;  
      mask <<= idx; 
     } 
} 
+0

建議'if(idx> = CHAR_BIT)'(或某物),否則奇數CHAR_BIT會導致無限循環。 – chux

+0

我曾試圖使這個代碼 – user6719757

+0

仍然不工作...我錯過了一些東西......這個想法是保持偶數位和奇數位分開,並將偶數位的索引切換到奇數位(相對於奇數位偶數位) – user6719757

0
char codeBinPair(char str) 
{ 

    int idx = CHAR_BIT - 1; 
    char mask = 1; 
    char maskA = 0; 
    char maskB = 0; 
    // str = 'W' 
    while (idx--) // Loop 7 times = 7 bits in char 
    { 
     //To Replace the odd bits 
     maskA |= mask & str; 
     mask <<= 1; 
     //To Replace the even bits 
     maskB |= mask & str; 
     mask <<= 1; 
    } 
    // to shift ths bits of 2 masks 
    maskA <<= 1; 
    maskB >>= 1; 
    // Subtraction between the 2 masks will give the encoded 
    return maskA - maskB;} 

    } 
+0

爲了使其成爲一個有用的答案,您需要解釋原始代碼的錯誤以及該版本如何修復它。只是傾銷一堆代碼將無助於讀者理解。 – Barmar

+0

您仍然使用'char'而不是'unsigned char',所以它可以被簽名,然後您的位操作可能無法按預期工作。 – Barmar

+0

我明白你是對的...... – user6719757

相關問題