小数在C 8位二进制转换++ [英] decimal to 8 bit binary conversion in c++

查看:149
本文介绍了小数在C 8位二进制转换++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作十进制到二进制的转换。我可以将它们转换,使用
炭bin_x [10];
  itoa(X,bin_x,2);
但问题是,我想在8位回答。它给了我,例如X = 5,那么输出将是101,但我想00000101。
有什么办法来追加零数组的开始?或是否有可能在8位得到答案马上?我在C ++这样

I am working on decimal to binary conversion. I can convert them, using char bin_x [10]; itoa (x,bin_x,2); but the problem is, i want answer in 8 bits. And it gives me as, for example x =5, so output will be 101, but i want 00000101. Is there any way to append zeros in the start of array? or is it possible to get answer in 8 bits straight away? I am doing this in C++

推荐答案

在C ++中,最简单的方法是的可能的使用和std :: bitset

In C++, the easiest way is probably to use a std::bitset:

#include <iostream>
#include <bitset>

int main() { 
    int x = 5;

    std::bitset<8> bin_x(x);
    std::cout << bin_x;

    return 0;
}

结果:

00000101

这篇关于小数在C 8位二进制转换++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆