【问题标题】:printing the binary representation of signed ints打印带符号整数的二进制表示
【发布时间】:2015-01-12 01:16:58
【问题描述】:

我需要一个函数来打印带符号 int 的二进制表示,我有以下对负整数和正整数都有效的函数,因为1 << 31 = 2147483648 的无符号值,这是一种有效的方法吗? ?

#include <stdio.h>

void printBinary(int n) {

    for (unsigned i = 1 << 31; i > 0; i = i >> 1) {
        if (i & n) {
            printf("1");
        } else {
            printf("0");
        }
    }
    printf("\n");
}

int main() {

    printBinary(2147483647); // 01111111111111111111111111111111
    printBinary(-2147483647); // 10000000000000000000000000000001
    printBinary(-2147483648); // 10000000000000000000000000000000
    printBinary(2147483648); // can't be represented, will produce wrong results
    return 0;
}

【问题讨论】:

  • std::bitset::to_string() 恕我直言,这是最简单的方法。
  • 因为它大于有符号整数...
  • 如果printBinaryunsigned int 作为参数,您可能会更开心。有符号整数以可预测的方式转换为无符号整数;反之则不成立(有符号整数溢出表现出未定义的行为)。
  • 是的,它打印错误的结果,我会改变它
  • @IgorTandetnik 将无符号整数转换为有符号整数不是 UB,而是最多定义的实现。见 [conv.integral]/3。

标签: c++ c binary


【解决方案1】:

你应该试试这个:

http://www.cplusplus.com/reference/cstdlib/itoa/

它适用于有符号整数。

如果编译器抱怨它已被弃用,请使用此函数: _itoa_s

小例子:

#include <stdio.h>
#include <stdlib.h>

int _tmain(int argc, _TCHAR* argv[])
{
    char bin[33];
    _itoa_s(-5456,bin,2);
    printf("%s",bin);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-12
    • 2013-11-18
    • 2018-04-29
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2012-02-23
    • 2015-11-30
    相关资源
    最近更新 更多