gpt4 book ai didi

有符号十进制数的 char* 到 2s 补码二进制表示的 char*?

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

因此有一个可以用 16 位表示的有符号十进制数,在 char* 中。我想要在 2 补码二进制中拥有该数字的 char* 。所以我想在C中从“-42”到“1111111111010110”(注意显示所有16位)。有没有一种快速而肮脏的方法来做到这一点?也许是一些库函数?或者我必须自己编写一个大型函数才能做到这一点?

我知道 strtol() 可能有一些用处。

最佳答案

没有一个标准库函数可以生成您所描述的二进制字符串。

不过,这并不是特别难做到。

#include <stdio.h>
#include <stdint.h>
#include <ctype.h>

int main(int argc, char ** argv)
{
while(--argc >= 0 && ++argv && *argv){
char const * input = *argv;
if(! input)
continue;

uint32_t value = 0;
char negative = 0;
for(; *input; input++){
if (isdigit(*input))
value = value * 10 + (*input -'0');
else if (*input == '-' && value == 0)
negative = 1;
else {
printf("Error: unexpected character: %c at %d\n", *input, (int)(input - *argv));
continue; // this function doesn't handle floats, or hex
}
}

if (value > 0x7fff + negative){
printf("Error: value too large for 16bit integer: %d %x\n", value, value);
continue; // can't be represented in 16 bits
}

int16_t result = value;
if (negative)
result = -value;

for (int i=1; i <= 16; i++)
printf("%d", 0 != (result & 1 << (16-i)) );

printf("\n");
}
}

该函数处理所有有效的 16 位值,并利用架构将整数存储为二进制补码值的事实。我不知道有哪个架构不这样做,所以这是一个相当合理的假设。

请注意,二进制补码 INT_MIN != -1 * INT_MAX。这是通过在从无符号 32 位转换为有符号 16 位之前向有效性检查添加否定标志来处理的。

./foo 1 -1 2 -2 42 -42 32767 -32767 32768 -32768
0000000000000001
1111111111111111
0000000000000010
1111111111111110
0000000000101010
1111111111010110
0111111111111111
1000000000000001
Error: value too large for 16bit integer: 32768 8000
1000000000000000

关于有符号十进制数的 char* 到 2s 补码二进制表示的 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42426946/

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