简体   繁体   English

C-如何将数组中的任何组合char或int连接到int或char类型的二进制字符串

[英]C - How to concatenate any combination char or int in array to binary string of type int or char

Brand new to the board. 全新的董事会。 I really try to solve my programming conundrums without bogging down a public forum, and stackoverflow has helped with many a problem, but I'm at a loss. 我确实试图解决我的编程难题,而不会陷入公共论坛的泥潭​​,而stackoverflow解决了许多问题,但是我很茫然。 I hope you can help. 希望您能提供帮助。

I am attempting to concatenate/combine, single digit characters in an array into a variable that takes the form of a binary string of format 10101010. There is no arithmetic involved and all characters are single-digit 1s and 0s. 我正在尝试将数组中的一位数字字符连接/组合为一个变量,该变量采用格式为10101010的二进制字符串的形式。不涉及任何算术运算,所有字符均为一位数字1和0。 I have scoured the Web for a solution and I have tried everything from strcat(), otoi(), sprintf(), etc. I have even tried using a String array[] to construct my variable and then convert type using strtoul(). 我在网上搜寻解决方案,并且尝试了strcat(),otoi(),sprintf()等的所有内容。甚至尝试使用String array []构造变量,然后使用strtoul()转换类型。 。 The code below reflects my latest attempt, which compiles successfully, but appears to produce blank characters. 下面的代码反映了我的最新尝试,该尝试已成功编译,但似乎会产生空白字符。 Understanding that I may be way off track with this solution, I am open to any solution that works. 了解到我可能无法使用该解决方案,因此我对任何可行的解决方案持开放态度。

The code: 编码:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <stdlib.h>

char digit[48] = "";

char buf[9];
snprintf(buf, sizeof buf, "%s%c", digit[16], digit[17], digit[18], digit[19], digit[20],_ 
digit[21], digit[22], digit[23]);

As you can see, the idea is to be able to take any digits from char digit[48] and combine them into the desired format. 如您所见,该想法是能够从char digit[48]获取任何数字并将其组合为所需的格式。 Truthfully, I'm not interested in adding the characters into a new array, but I got to the point of trying anything. 说实话,我对将字符添加到新数组中不感兴趣,但是我想尝试任何东西。 My preference is to have the result accessible via a single variable to then use for bitwise operations and direct input into integrated components. 我的首选是通过单个变量访问结果,然后将其用于按位运算并直接输入到集成组件中。 Than you for any assistance you can provide. 比你的任何援助可以提供。

Take a look at Converting an int into a base 2 cstring/string 看看将int转换为以2为底的cstring / string

and note (if you're using Linux) that I believe the deprecated function name there is _itoa. 并注意(如果您使用的是Linux)我相信不推荐使用的函数名是_itoa。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM