问题描述
我正在尝试显示int16_t的Two's Complement的字符串表示形式。我用(uint16_t)~value + 1;
如何将16位添加到字符串中?
char* getBits(const int16_t value) {
uint16_t complement = (uint16_t)~value + 1;
char bits = malloc(16*sizeof(char*))
for (int i = 0; i < 16; i++) {
bits[i] = // something
}
return bits;
}
解决方法
将complement
向右移i
位,并测试低阶位是0
还是1
并将相应的字符放在bits
中。 / p>
bits[i] = (complement >> i) & 1 ? '1' : '0';
此外,您需要在字符串中为空终止符分配一个额外的字符。并且bits
必须是一个指针,而元素大小是sizeof(char)
,而不是sizeof(char*)
。
char *bits = malloc(17*sizeof(char));
bits[16] = 0;
无需使用公式(uint16_t)~value + 1
。将带符号的int转换为无符号的int会自动返回其二进制补码值。因此,您只需执行以下操作即可:
uint16_t complement = (uint16_t)value;
,
您的代码有很多问题,甚至无法编译。您需要学习什么是指针,什么不是指针。如何使用malloc以及将其结果存储在何处。最好的方法是阅读一本好书。
#include <stdint.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
char* getBits(const int16_t value)
{
uint16_t complement = value;
char *bits = malloc(sizeof(value) * CHAR_BIT + 1);
char *wrk = bits;
if(bits)
{
for (unsigned i = 1 << 15; i; i >>= 1)
{
*wrk++ = (complement & i) ? '1' : '0';
}
*wrk++ = 0;
}
return bits;
}
int main(void)
{
for(int i = 0; i > -15; i --)
{
char *bits;
printf("%d - %s\n",i,(bits = getBits(i)));
free(bits);
}
}