user6719757 user6719757 - 3 months ago 11
C Question

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

'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).
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;
}
}

Answer

Change all the char in codeBinPair to 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;
        }
}
Comments