简体   繁体   中英

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. 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. 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(). 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. 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

and note (if you're using Linux) that I believe the deprecated function name there is _itoa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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