在C / Arduino的INT转换为二进制 [英] Converting int to binary in C / Arduino

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

问题描述

我有一个很艰难的时间,试图为INT转换为8位二进制数。

I'm having a really hard time trying to convert an INT to an 8 bit Binary number.

还有大量code对如何做到这一点但是网上大多数人需要的库才能工作,而Arduino的不从C支持库,它有自己的。

There's plenty of code on how to do this online however most of them need libraries in order to work, and Arduino doesn't support libraries from C as it has its own.

如果任何人有关于如何去这样做不使用C库,也许只是使用一些循环任何想法,这将是pciated多少AP $ P $

If anyone has any idea on how to go about doing this without using C libraries, maybe just using some loops, it would be much appreciated

例如:

如果输入是5
输出应该是00000101

if the input is 5 the output should be 00000101

感谢

推荐答案

您可以打印使用按位整数的二进制值。

You can print the binary value of an integer using the bitwise.

至于我而言,我使用这种功能,了解它是如何工作的:

As far as I am concerned, I'm using this kind of function to understand how it works :

int     main()
{
  int   nb = 10;
  int   i = 31;

  while (i >= 0) {
    if ((nb >> i) & 1)
      printf("1");
    else
      printf("0");
    --i;
  }
  printf("\n");
}

在此code,在重新presents所选位。有了这个选择一点,我在寻找,如果它使用逻辑与(安培)是一个1运营商。如果是的,我打印1和我选择下位,直到数量的端部(其中包含32位,因为它是一个整数)。

In this code, the i represents the selected bit. With this selected bit, I'm searching if it's a 1 using the logical AND (&) operator. If it is, I print "1" and I select the next bit until the end of the number (which contains 32 bits, because it's an integer).

有很多是采用的方式按位..你已经自己尝试一下更好地理解获得价值!

There is many way to obtain the value using the bitwise.. You have to try it yourself to understand better !

祝你好运!

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

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