简体   繁体   English

我如何在C函数中像无符号的那样使带符号的字符

[英]How can I make to signed char in C function like unsigned

I'm trying to encode_char_in C that replace the bit of even index between the odd bit index, like this 我正在尝试对奇数位索引之间的偶数索引位进行替换的encode_char_in C,像这样

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

and because char in C may become to negative number, I can't switch between the bits (only in signed char — it works). 而且由于C中的char可能变为负数,所以我无法在位之间切换(仅在带signed char起作用)。 It gave me another value in this code below. 在下面的代码中,它给了我另一个价值。

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

Change all the char in codeBinPair to unsigned char . codeBinPair所有char更改为unsigned 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;
        }
}
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;}

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM