I want to store the binary value of each character in a string and store it in an array. But when i start messing around with functions like memset
, i have no control over the debugging.
#include <stdio.h>
#include <string.h>
int main()
{
char str[8];
char *ptr = "Hello";
int i;
for(; *ptr != 0; ++ptr)
{
printf("%c => ", *ptr);
/* perform bitwise AND for every bit of the character */
for(i = 7; i >= 0; --i)
if(*ptr & 1 << i)
str[7-i]='1';
else
str[7-i]='0';
//(*ptr & 1 << i) ? putchar('1') : putchar('0');
str[8]='\0';
printf("%s\n",str);
memset(str,'/0',8);
}
return 0;
}
Output:
H => 01001000
e => 01100101
l => 01101100
l => 01101100
o => 01101111
Abort trap
It would be nice if someone can throw some light. Even though i am getting the output, the trap is happening.
Courtesy: This is a modified program of a fellow stack fellow user @Athabaska.