How convert string to binary - c

Im cant understand whats wrong with my code. All start to work good, but when my phrase "Hello, how are you" compiled, it start to print some other numbers and symbols.
Thank you in advance!your text
include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
void encode_string(const char string[], bool bytes[strlen(string)+1][8]){
for(int j = 0; j <= bytes[strlen(string)+1][8]; j++){
printf("%c: ", string[j]);
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( string[j] >> i ) & 1 ? 1 : 0 );
}
printf("\n");
}
}
int main(){
char* text = "Hello, how are you?";
const int len = strlen(text);
bool bytes1[len+1][8];
encode_string(text, bytes1);
for(int j = 0; j <= len; j++){
printf("%c: ", text[j]);
for(int i = 0; i < 8; i++){
printf("%d", bytes1[j][i]);
}
printf("\n");
}
}

You're not allocating memory to string which you are passing. which leads to UB. I removed string size parameter in function encode_string
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
void encode_string(const char string[])
{
size_t len = strlen(string);
char *binary = malloc(len*8 + 1); //each char is one byte (8 bits) and + 1 at the end for null terminator
for(int j = 0; j <= len; j++){
printf("%c: ", string[j]);
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( string[j] >> i ) & 1 ? 1 : 0 );
}
printf("\n");
}
}
int main(){
char* text = "Hello, how are you?";
const int len = strlen(text);
bool bytes1[len+1][8];
encode_string(text);
for(int j = 0; j <= len; j++){
printf("%c: ", text[j]);
for(int i = 0; i < 8; i++){
printf("%d", bytes1[j][i]);
}
printf("\n");
}
}
Output:
H: 01001000
e: 01100101
l: 01101100
l: 01101100
o: 01101111
,: 00101100
: 00100000
h: 01101000
o: 01101111
w: 01110111
: 00100000
a: 01100001
r: 01110010
e: 01100101
: 00100000
y: 01111001
o: 01101111
u: 01110101
?: 00111111
: 00000000
H: 192900192900
e: 192900192900
l: 192900192900
l: 192900192900
o: 192900192900
,: 192900192900
: 192900192900
h: 192900192900
o: 00000000
w: 010064000
: 000064000
a: 02000400
r: 00000000
e: 00000000
: 00000000
y: 00000000
o: 00000000
u: 00000000
?: 00000000
: 2151941531301348500
...Program finished with exit code 0
Press ENTER to exit console.

Related

A Problem I faced using Bitwise Operators in C (HackerRank)

HackerRank link
In this challenge, you will use logical bitwise operators. All data is stored in its binary representation. The logical operators, and C language, use 1 to represent true and 0 to represent false. The logical operators compare bits in two numbers and return true or false, 0 or 1, for each bit compared.
Bitwise AND operator & The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. It is denoted by &.
Bitwise OR operator | The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. It is denoted by |.
Bitwise XOR (exclusive OR) operator ^ The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^.
For example, for integers 3 and 5,
3 = 00000011 (In Binary)
5 = 00000101 (In Binary)
AND operation OR operation XOR operation
00000011 00000011 00000011
& 00000101 | 00000101 ^ 00000101
________ ________ ________
00000001 = 1 00000111 = 7 00000110 = 6
you will be given an integer n and a threshold, k. For each number, find the maximum value of the logical and,or and xor when compared against all integers through n.
Example
n=3
k=3
The Results of the comparisons are below:
a b and or xor
1 2 0 3 3
1 3 1 3 2
2 3 2 3 1
For the and comparison, the maximum is 2. For the or comparison, none of the values is less than k, so the maximum is 0. For the xor comparison, the maximum value less than k is 2. The function should print:
2
0
2
Function Description
Complete the calculate_the_maximum function in the editor below.
calculate_the_maximum has the following parameters:
int n: the highest number to consider
int n: the highest number to consider
Prints
Print the maximum values for the and, or and xor comparisons, each on a separate line.
Input Format
The only line contains 2 space-separated integers, n and k.
Constraints
2 <= n <= (10)^3
2 <= k <= n
Sample Input 0
5 4
*Sample Output 0
2
3
3
** So This is My Answer**
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void calculate_the_maximum(int n, int k) {
int m1=0,m2=0,m3=0;
for (int x=1; x<n; x++){
for (int y=2; y<=n; y++){
//and
int a=x&y;
if((a>m1) && (a<k)){
m1=a;
};
//or
int b=x|y;
if((b>m2) && (b<k)){
m2=b;
};
//xor
int c=x^y;
if((c>m3) && (c<k)){
m3=c;
};
}
}
printf("%d \n",m1);
printf("%d \n",m2);
printf("%d \n",m3);
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
calculate_the_maximum(n, k);
return 0;
}
And My Output is
3
3
3
Expected Output
2
3
3
What is the mistake of my code?
This was my answer
I first converted to binary then converted it back
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
void calculate_the_maximum(int n, int k)
{
int i,j,a,b;
int max_and = 0;
int max_or = 0;
int max_xor = 0;
for (i = 1; i < n+1; i++)
{
for (j = 1; j < n+1; j++)
{
if (j>i)
{
a = i;
b = j;
int count_1 = 0;
int sum_1 = 0;
int count_2 = 0;
int sum_2 = 0;
while (!(a==0))
{
sum_1 += (a%2)*(pow(10,count_1));
a = a/2;
count_1++;
}
while (!(b==0))
{
sum_2 += (b%2)*(pow(10,count_2));
b = b/2;
count_2++;
}
int sum_3 = 0;
int sum_4 = 0;
int sum_5 = 0;
int num_1 = 0;
int num_2 = 0;
int num_3 =0;
int count_3 = 0;
while (!((sum_1 == 0)&&(sum_2 == 0)))
{
if ((sum_1%10 == 1)&&(sum_2%10 == 1))
{
sum_3 += pow(10,count_3);
}
if ((sum_1%10 == 1)||(sum_2%10 == 1))
{
sum_4 += pow(10,count_3);
}
if (((sum_1%10 == 1)&&(sum_2%10 == 0))||((sum_1%10 == 0)&&(sum_2%10 == 1)))
{
sum_5 += pow(10,count_3);
}
sum_1 = sum_1/10;
sum_2 = sum_2/10;
count_3++;
}
int count_4 = 0;
while (!(sum_3 == 0))
{
num_1 += (sum_3%10)*(pow(2,count_4));
sum_3 = sum_3/10;
count_4++;
}
int count_5 = 0;
while (!(sum_4 == 0))
{
num_2 += (sum_4%10)*(pow(2,count_5));
sum_4 = sum_4/10;
count_5++;
}
int count_6 = 0;
while (!(sum_5 == 0))
{
num_3 += (sum_5%10)*(pow(2,count_6));
sum_5 = sum_5/10;
count_6++;
}
if ((max_and < num_1)&&(num_1<k))
{
max_and = num_1;
}
if ((max_or < num_2)&&(num_2<k))
{
max_or = num_2;
}
if ((max_xor < num_3)&&(num_3<k))
{
max_xor = num_3;
}
}
}
}
printf("%d\n%d\n%d",max_and,max_or,max_xor);
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
if (!((n < 2)||(n > 1000)||(k < 2)||(k >n)))
{
calculate_the_maximum(n, k);
return 0;
}
else
{
printf("Error!\n");
return 1;
}
}
You shouldn't initialize "y" at 2. In your case, i and y can be the same values.
when i = 2, y can be equal to 2. But you cannot do this for the question. Start y from i+1.
void calculate_the_maximum(int n, int k)
{
int max_or = 0;
int max_and = 0;
int max_xor = 0;
int temp_xor = 0;
int temp_and = 0;
int temp_or = 0;
//or = xor + and;
for(int i = 1 ; i < n ; i++ )
{
for(int j = i+1 ; j <=n ; j++)
{
temp_xor = i ^ j;
temp_and = i & j;
temp_or = temp_xor + temp_and;
if (temp_xor > max_xor && temp_xor < k) max_xor = temp_xor;
if (temp_and > max_and && temp_and < k) max_and = temp_and;
if (temp_or > max_or && temp_or < k) max_or = temp_or;
}
}
//print
cout << max_and << endl << max_or << endl << max_xor;
}
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void calculate_the_maximum(int n, int k) {
int m1=0,m2=0,m3=0;
for (int x=1; x<n; x++){
for (int y=x+1; y<=n; y++){
//and
int a= x & y;
if((a>m1) && (a<k)){
m1=a;
};
//or
int b=x|y;
if((b>m2) && (b<k)){
m2=b;
};
//xor
int c=x^y;
if((c>m3) && (c<k)){
m3=c;
};
}
}
printf("%d \n",m1);
printf("%d \n",m2);
printf("%d \n",m3);
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
calculate_the_maximum(n, k);
return 0;
}

Convert words to binary values

I need to convert words to binary numbers, positioned vertically (\n).
I need to write a function, which will do this convert.. Below is a sample..
Can you help me please?
//main
char* text = "Hello, how are you?";
const int len = strlen(text);
bool bytes1[len+1][8];
encode_string(text, bytes1);
for(int j = 0; j <= len; j++){
printf("%c: ", text[j]);
for(int i = 0; i < 8; i++){
printf("%d", bytes1[j][i]);
}
printf("\n");
}
// prints:
// H: 01001000
// e: 01100101
// l: 01101100
// l: 01101100
// o: 01101111
// ,: 00101100
// : 00100000
// h: 01101000
// o: 01101111
// w: 01110111
// : 00100000
// a: 01100001
// r: 01110010
// e: 01100101
// : 00100000
// y: 01111001
// o: 01101111
// u: 01110101
// ?: 00111111
// : 00000000
//function
void encode_string(const char string[], bool bytes[strlen(string)+1][8]){
}
Hy man you can use this:
Converting every char:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main(void){
char* text = "Hello, how are you?";
int len_size = strlen(text);
for(int j = 0; j <= len_size; j++){
printf("%c: ", text[j]);
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( text[j] >> i ) & 1 ? 1 : 0 );
}
printf("\n");
}
return 0;
}
Onother option with your function:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
void encode_string(char string[], int len_size);
int main(void){
char* text = "Hello, how are you?";
int len_size = strlen(text);
encode_string(text, len_size);
return 0;
}
void encode_string(char string[], int len_size){
for(int j = 0; j <= len_size; j++){
printf("%c: ", string[j]);
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( string[j] >> i ) & 1 ? 1 : 0 );
}
printf("\n");
}
}
I know your error already, your are trying to send to the function, and you dont send the right parameters...

Count Sort in C - problem with output and count_array

I am trying to implement a count sort algorithm in C for uni. The task was pretty easy because we were given pseudocode to translate into c-code. But somehow my count_array and output_array go crazy. But i don't see where i am writing in indices i am not supposed to or where there is a memory fault.
Edit: The console gives out the following
Unsortiertes Array:(print input_array) 90 38 42 34 8 0 77 1 84 5 25 72 44 42 90 63 23
(print count_array) -363607072 32766 233318081 1 1 0 0 0 -363606696 32766 -363606200 32766 1805418521 32767 13 0 0
Sortiertes Array: print output_array) 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
What am i doing wrong? i think it is the output_array[k] = j; in count_sort_write_output_array but when i look up other counting sort algos on the internet thats how its supposed to be written, or not?
#include <stdio.h>
#include <stdlib.h>
#include "arrayio.h"
int MAX_LAENGE = 1000;
int MAX_VALUE = 100;
int j, i, k;
void count_sort_calculate_counts(int input_array[], int len, int count_array[]) {
for (j = 0; j < len; j++) {
count_array[input_array[j]] = count_array[input_array[j]] + 1;
}
}
void count_sort_write_output_array(int output_array[], int len, int count_array[]) {
k = 0;
for (j = 0; j < len; j++) {
for (i = 0; i < count_array[j]; i++) {
output_array[k] = j;
k = k + 1;
}
}
}
int main(int argc, char *argv[]) {
if (argc < 2){
printf("Aufruf: %s <Dateiname>\n", argv[0]);
printf("Beispiel: %s zahlen.txt\n", argv[0]);
exit(1);
}
char *filename = argv[1];
int input_array[MAX_LAENGE];
int len = read_array_from_file(input_array, MAX_LAENGE, filename);
printf("Unsortiertes Array:");
print_array(input_array, len);
int count_array[MAX_LAENGE];
// print_array(count_array, len);
int output_array[MAX_LAENGE];
count_sort_calculate_counts(input_array, len, count_array);
count_sort_write_output_array(output_array, len, count_array);
printf("Sortiertes Array:");
print_array(output_array, len);
return 0;
}

The simple transition of matrix but what went wrong?

#include <stdio.h>
main(){
int A[3][2] = {0} ;
printf("A = \n");
for(int x = 0 ; x < 3 ; x++){
for (int y = 0 ; y < 2 ; y ++){
A[x][y] = (x+1)*1 + (x*1+3)*y ;
printf("A[%d][%d] = %d ", x , y ,A[x][y]);
}
printf("\n");
}
printf("\nAT = \n");
for (int p = 0 ; p < 2 ; p++){
for (int q = 0 ; q < 3 ; q++){
A[p][q] = A[q][p];
printf("A[%d][%d] = %d ", p ,q , A[p][q]);
}
printf("\n");
}
}
Why does AT[1][0] = 2 not 4?
I have tested it for an hour for this simple question, but I have no idea.
If you transpose a non-square matrix then the dimensions of the resulting matrix will also be transposed. Not only that, if you were going to transpose in-place you would need to swap pairs of elements, otherwise you would be overwriting some of the elements before they had been transposed.
So, to solve both these problems you should probably just use a second matrix with the correct dimensions for the transposed result, e.g.
#include <stdio.h>
int main()
{
int A[3][2] = {0};
int AT[2][3] = {0}; // <<<
printf("A = \n");
for(int x = 0 ; x < 3 ; x++){
for (int y = 0 ; y < 2 ; y ++){
A[x][y] = (x+1)*1 + (x*1+3)*y ;
printf("A[%d][%d] = %d ", x, y, A[x][y]);
}
printf("\n");
}
printf("\nAT = \n");
for (int p = 0 ; p < 2 ; p++){
for (int q = 0 ; q < 3 ; q++){
AT[p][q] = A[q][p]; // <<<
printf("A[%d][%d] = %d ", p, q, AT[p][q]);
}
printf("\n");
}
return 0;
}
LIVE DEMO
You are accessing the array out of bounds when the condition came,
A[0][2]=A[2][0]; // <--
Here You can access only until first location. So as like Paul R says Use the
separate array when you transpose the array.
For example consider your array is declared in memory like this.
Memory Address 125 126 127 128 129 130
^ ^ ^ ^ ^ ^
| | | | | |
Array accessing [0][0] [0][1] [1][0] [1][1] [2][0] [2][1]
what will happen when you are accessing the [0][2]. It will go to the [1][0].

Varying number of for-loops

I'm trying to write a code that could print something like this
-xv
-xvv
-xvvv
-xvvvv
-xvvvvv
-xxv
-xxvv
-xxvvv
-xxvvvv
-xxvvvvv
-xxxv
-xxxvv
-xxxvvv
-xxxvvvv
-xxxvvvvv
The extra spacing between the 3 "groups" are just for clarity's sake. The maximum number of '-' is 1, 'x' is 3, 'v' is 5, and the number of each symbol increments.
To draw this diagram, I have the following code
for (k = 1 ; k <= num_dash ; k++)
{
for (i = 1 ; i <= num_x ; i++)
{
for (j = 1 ; j <= num_v ; j+++)
{
for (k1 = 0 ; k1 < k ; k++)
printf("-");
for (i1 = 0 ; i1 < i ; i++)
printf("x");
for (j1 = 0 ; j1 < j ; j++)
printf("v");
printf("\n");
}
}
}
This is when I know there are 3 different kinds of symbols. Is it possible to do the same if the number of symbols are only known at runtime? For example, what if I want the same program to also be able to print
xv
xvv
xvvv
xvvvv
xvvvvv
xxv
xxvv
xxvvv
xxvvvv
xxvvvvv
xxxv
xxxvv
xxxvvv
xxxvvvv
xxxvvvvv
In this case, my code would only be
for (i = 1 ; i <= num_x ; i++)
{
for (j = 1 ; j <= num_v ; j+++)
{
for (i1 = 0 ; i1 < i ; i++)
printf("x");
for (j1 = 0 ; j1 < j ; j++)
printf("v");
printf("\n");
}
}
And there are only 2 for-loops instead of 3. Can I write my code such that the number of for-loops varies?
Use functions instead of innermost for loops and pass the characters and number of iterations as parameters to that function.
E.g.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_aux(char **symbols, int *times, int len, int pos, char *acc){
int i;
char *p;
if(pos == len){
printf("%s\n", acc);
return;
}
p = malloc(sizeof(char)*strlen(symbols[pos])*times[pos]+strlen(acc)+1);
for(i=0;i<times[pos];++i){
int j;
*p='\0';
strcpy(p, acc);
for(j=0;j<=i;++j){
strcat(p, symbols[pos]);
}
print_aux(symbols, times, len, pos + 1, p);
}
if(pos + 1 == len)// when last symbol
printf("\n",pos);
free(p);
}
//wrap function
void print(char **symbols, int *times, int len){
print_aux(symbols, times, len, 0, "");
}
int main() {
int i,n;
char **symbols;
int *times;
fprintf(stderr,"number of symbols :");
scanf("%d", &n);
symbols=(char**)malloc(sizeof(char*)*n);
times = (int*)malloc(sizeof(int)*n);
for(i=0;i<n;++i){
char wk[128];
fprintf(stderr,"input symbol [%d]:", i+1);
scanf(" %s", wk);
symbols[i] = strdup(wk);
fprintf(stderr,"maximum number of \"%s\":",wk);
scanf(" %d", &times[i]);
}
print(symbols, times, n);
{ //release the allocated area
for(i=0;i<n;++i){
free(symbols[i]);
}
free(symbols);
free(times);
}
return 0;
}

Resources