Your code seems to be mostly fine. You are only really mallocing the wrong amount. Here it is wth the corrections:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* stringToBinary(char* s) {
if(s == NULL) return 0; /* no input string */
size_t len = strlen(s);
char *binary = malloc(len*8 + 1); // each char is one byte (8 bits) and + 1 at the end for null terminator
binary[0] = '\0';
for(size_t i = 0; i < len; ++i) {
char ch = s[i];
for(int j = 7; j >= 0; --j){
if(ch & (1 << j)) {
strcat(binary,"1");
} else {
strcat(binary,"0");
}
}
}
return binary;
}
Sample runs:
"asdf" => 01100001011100110110010001100110
"tester" => 011101000110010101110011011101000110010101110010
"Happy New Year" => 0100100001100001011100000111000001111001001000000100111001100101011101110010000001011001011001010110000101110010
Answer from gowrath on Stack OverflowYour code seems to be mostly fine. You are only really mallocing the wrong amount. Here it is wth the corrections:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* stringToBinary(char* s) {
if(s == NULL) return 0; /* no input string */
size_t len = strlen(s);
char *binary = malloc(len*8 + 1); // each char is one byte (8 bits) and + 1 at the end for null terminator
binary[0] = '\0';
for(size_t i = 0; i < len; ++i) {
char ch = s[i];
for(int j = 7; j >= 0; --j){
if(ch & (1 << j)) {
strcat(binary,"1");
} else {
strcat(binary,"0");
}
}
}
return binary;
}
Sample runs:
"asdf" => 01100001011100110110010001100110
"tester" => 011101000110010101110011011101000110010101110010
"Happy New Year" => 0100100001100001011100000111000001111001001000000100111001100101011101110010000001011001011001010110000101110010
Without any assumptions about the input, just printing the bits in the bytes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
char *stringToBinary(char *s)
{
if (s == NULL) {
// NULL might be 0 but you cannot be sure about it
return NULL;
}
// get length of string without NUL
size_t slen = strlen(s);
// we cannot do that here, why?
// if(slen == 0){ return s;}
errno = 0;
// allocate "slen" (number of characters in string without NUL)
// times the number of bits in a "char" plus one byte for the NUL
// at the end of the return value
char *binary = malloc(slen * CHAR_BIT + 1);
if(binary == NULL){
fprintf(stderr,"malloc has failed in stringToBinary(%s): %s\n",s, strerror(errno));
return NULL;
}
// finally we can put our shortcut from above here
if (slen == 0) {
*binary = '\0';
return binary;
}
char *ptr;
// keep an eye on the beginning
char *start = binary;
int i;
// loop over the input-characters
for (ptr = s; *ptr != '\0'; ptr++) {
/* perform bitwise AND for every bit of the character */
// loop over the input-character bits
for (i = CHAR_BIT - 1; i >= 0; i--, binary++) {
*binary = (*ptr & 1 << i) ? '1' : '0';
}
}
// finalize return value
*binary = '\0';
// reset pointer to beginning
binary = start;
return binary;
}
int main(int argc, char **argv)
{
char *output;
if (argc != 2) {
fprintf(stderr, "Usage: %s string\n", argv[0]);
exit(EXIT_FAILURE);
}
// TODO: check argv[1]
output = stringToBinary(argv[1]);
printf("%s\n", output);
free(output);
exit(EXIT_SUCCESS);
}
Converting C string to binary representation - Stack Overflow
c - How to convert a string to binary? - Stack Overflow
string - Conversion of Char to Binary in C - Stack Overflow
c - How convert string to binary - Stack Overflow
Or did you mean how to convert C string to binary representation?
Here is one solution which can convert strings to binary representation. It can be easily altered to save the binary strings into array of strings.
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argv[1] == NULL) return 0; /* no input string */
char *ptr = argv[1];
int i;
for(; *ptr != 0; ++ptr)
{
printf("%c => ", *ptr);
/* perform bitwise AND for every bit of the character */
for(i = 7; i >= 0; --i)
(*ptr & 1 << i) ? putchar('1') : putchar('0');
putchar('\n');
}
return 0;
}
Example input & output:
./ascii2bin hello
h => 01101000
e => 01100101
l => 01101100
l => 01101100
o => 01101111
There is no any strings in C. Any string IS an array of bytes.
The easiest way will be using a bit field:
struct code {
unsigned opcode : 6;
unisgned operand1 : 5;
unisgned operand2 : 5;
unisgned operand2 : 5;
} test_code;
Now you can simply assign to the different members:
test_code.opcode = 0x02;
test_code.operator1 = 0x01;
test_code.operator2 = 0x02;
test_code.operator3 = 0x03;
atoi(op) will give you 2, so you can just string it together
As far as putting it into that structure you want, just create a structure that has bitfields in it and place it in a union with a 32 bit unsigned integer, and you can take the value directly.
We show up two functions that prints a SINGLE character to binary.
void printbinchar(char character)
{
char output[9];
itoa(character, output, 2);
printf("%s\n", output);
}
printbinchar(10) will write into the console
1010
itoa is a library function that converts a single integer value to a string with the specified base. For example... itoa(1341, output, 10) will write in output string "1341". And of course itoa(9, output, 2) will write in the output string "1001".
The next function will print into the standard output the full binary representation of a character, that is, it will print all 8 bits, also if the higher bits are zero.
void printbincharpad(char c)
{
for (int i = 7; i >= 0; --i)
{
putchar( (c & (1 << i)) ? '1' : '0' );
}
putchar('\n');
}
printbincharpad(10) will write into the console
00001010
Now i present a function that prints out an entire string (without last null character).
void printstringasbinary(char* s)
{
// A small 9 characters buffer we use to perform the conversion
char output[9];
// Until the first character pointed by s is not a null character
// that indicates end of string...
while (*s)
{
// Convert the first character of the string to binary using itoa.
// Characters in c are just 8 bit integers, at least, in noawdays computers.
itoa(*s, output, 2);
// print out our string and let's write a new line.
puts(output);
// we advance our string by one character,
// If our original string was "ABC" now we are pointing at "BC".
++s;
}
}
Consider however that itoa don't adds padding zeroes, so printstringasbinary("AB1") will print something like:
1000001
1000010
110001
unsigned char c;
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}
printf("\n");
Explanation:
With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.
For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.
I need help to figure out how to convert string to binary. I though my code would work but it didn't
I don't quite get why this isn't working.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
const int BITS_IN_BYTE = 8;
void print_bulb(int bit);
int main(void)
{
string message = get_string("Message? ");
string binary = "";
for (int i = 0; i < strlen(message); i++)
{
if (message[i] % 2 == 0)
{
binary = 0 + "binary";
}
else if (message[i] % 2 == 1)
{
binary = 1 + "binary";
}
}
printf("%s\n", binary);
}
void print_bulb(int bit)
{
if (bit == 0)
{
// Dark emoji
printf("\U000026AB");
}
else if (bit == 1)
{
// Light emoji
printf("\U0001F7E1");
}
}Learning C currrently could use a little help. I'm still new to programming so the simpler the better.
So I'm having a lot of difficulty wrapping my head around this problem.
I'm trying to write a function that will convert a hexadecimal string (0123456789abcdef) into binary (0000 0001 .......).
Been stuck for several hours trying to figure out a solution. Any help will be greatly appreciated.
I have tried to modify your solution with minimal changes to make it work. There are elegant solutions to convert Integer to Binary for example using shift operators.
One of the main issue in the code was you were using character instead of character array.
i.e char str; instead of char str[SIZE];
Also you were performing string operations on a single character. Additionally, iostream header file is for C++.
There is room for lot of improvements in the solution posted below (I only made your code work with minimal changes).
My suggestion is to make your C basics strong and approach this problem again.
#include <stdio.h>
#include <string.h>
void converttobinary(int n, char *op)
{
int i;
int a[8];
for (i = 0; i < 8; i++)
{
a[i] = n % 2;
n = (n - a[i]) / 2;
}
for (i = 7; i >= 0; i--)
{
op[i]=a[i];
}
}
int main()
{
int n,i;
char str[8];
n = 8;
converttobinary(n,str);
for (i = 7; i >= 0; i--)
{
printf(" %d ",str[i]);
}
return 0;
}
char *rev(char *str)
{
char *end = str + strlen(str) - 1;
char *saved = str;
while(end > str)
{
int tmp = *str;
*str++ = *end;
*end-- = tmp;
}
return saved;
}
char *tobin(char *buff, unsigned long long data)
{
char *saved = buff;
while(data)
{
*buff++ = (data & 1) + '0';
data >>= 1;
}
*buff = 0;
return rev(saved);
}
int main()
{
char x[128];
unsigned long long z = 0x103;
printf("%llu is 0b%s\n", z, tobin(x, z));
return 0;
}