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 ascii string to binary? - Stack Overflow
c - How to convert a string to binary? - Stack Overflow
c - Binary string to integer and integer to binary string - Code Review Stack Exchange
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.
You could change the for loop to something like this:
for(i = 0; i < len; i++) {
unsigned char ch = input[i];
char *o = *out + 8 * i;
int b;
for (b = 7; b >= 0; b--)
*o++ = (ch & (1 << b)) ? '1' : '0';
}
or similar:
for(i = 0; i < len; i++) {
unsigned char ch = input[i];
char *o = &(*out)[8 * i];
unsigned char b;
for (b = 0x80; b; b >>= 1)
*o++ = ch & b ? '1' : '0';
}
This program gets and integer ( which contains 32 bits ) and converts it to binary, Work on it to get it work for ascii strings :
#include <stdio.h>
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n");
return 0;
}
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.
It makes sense for the two functions to be symmetrical - ie that you can call
them in turn to swap between integer and string representations. So I would
make binstr2int produce an unsigned long of full range returned through a
parameter and have the function return the status (0/-1):
int binstr2int(const char *s, unsigned long &num);
Note that s can be const.
In int2binstr I think the characters should be moved to the beginning of the
string - this is what all other C string functions do (or at least I'm
ignorant of any that do not). Also, your code is a bit awkward in
that it treats 0 separately from all other numbers. This is a case where a
do {...} while loop makes sense as it can handle the zero case as any other
number and test for zero once it has done it:
char* int2binstr(unsigned long num, char *s, size_t size)
{
long len = (long) size - 1;
do {
if (len <= 0) {
errno = ERANGE;
return NULL;
}
s[--len] = (num & 1) ? '1' : '0';
} while ((num >>= 1) != 0);
long n = (long) size - len - 1;
memmove(s, s + len, n);
s[n] = '\0';
return s;
}
Here you can see that the tests for a short input string and for
num == 0 are handled naturally. Also I moved the string into place after
creating it.
In int2binstr the comment says, "NULL returned on error check errno" but you don't return NULL on error: instead you return a pointer to an empty string.
Also, I find it unusual that int2binstr writes its result at the end of the passed-in buffer, instead of at the beginning.
Also, why use long in the first function but unsigned long in the second function.
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");
}
}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.
The line
string[i] = n & 1;
is assigning integers 0 or 1 to string[i]. They are typically different from the characters '0' and '1'. You should add '0' to convert the integers to characters.
Also, as @EugeneSh. pointed out, the line
n >> 1;
has no effect. It should be
n >>= 1;
to update the n's value.
Also, as @JohnnyMopp pointed out, you should terminate the string by adding a null-character.
One more point it that you should check if malloc() succeeded. (It is done in the function toBinaryString, but there is no check in main() before printing its result)
Finally, It doesn't looks so good to use a magic number 31 for the initialization of for loop while using sizeof(int) for the size for malloc().
Fixed code:
#include <stdio.h>
#include <stdlib.h>
char* toBinaryString(int n) {
int num_bits = sizeof(int) * 8;
char *string = malloc(num_bits + 1);
if (!string) {
return NULL;
}
for (int i = num_bits - 1; i >= 0; i--) {
string[i] = (n & 1) + '0';
n >>= 1;
}
string[num_bits] = '\0';
return string;
}
int main() {
char* string = toBinaryString(4);
if (string) {
printf("%s", string);
free(string);
} else {
fputs("toBinaryString() failed\n", stderr);
}
return 0;
}
The values you are putting into the string are either a binary zero or a binary one, when what you want is the digit 0 or the digit one. Try string[i] = (n & 1) + '0';. Binary 0 and 1 are non-printing characters, so that's why you get no output.
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;
}