gpt4 book ai didi

c - 如何在 C 函数中像 unsigned 那样生成有符号字符

转载 作者:行者123 更新时间:2023-11-30 16:58:19 25 4
gpt4 key购买 nike

我正在尝试在 C 中编码字符,替换奇数位索引之间的偶数索引位,如下所示

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

并且因为 C 中的 char 可能会变成负数,所以我无法在位之间切换(仅在 signed char 中 - 它有效)。它给了我另一种值(value)在下面的代码中。

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

最佳答案

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

关于c - 如何在 C 函数中像 unsigned 那样生成有符号字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38965194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com