Related
I am using Okamura's implementation of lzss : https://oku.edu.mie-u.ac.jp/~okumura/compression/lzss.c
int enc_i = 0;
int getbit(int n, unsigned char *enco_buf) /* get n bits */
{
int i, x;
static int buf, mask = 0;
x = 0;
for (i = 0; i < n; i++) {
if (mask == 0) {
//if ((buf = fgetc(infile)) == EOF) return EOF;
//if ((buf = fgetc(infile)) == EOF) return EOF;
if((buf = enco_buf[enc_i]) == '\0') break;
//buf = enco_buf[enc_i];
enc_i++;
//printf("\nValue of enc : %d\n", enc_i);
mask = 128;
}
x <<= 1;
if (buf & mask) x++;
mask >>= 1;
}
return x;
}
void decode(unsigned char *enco_buf)
{
int i, j, k, r, c;
outfile = fopen ("test_lib.txt", "wb");
for (i = 0; i < N - F; i++) buffer[i] = ' ';
r = N - F;
while ((c = getbit(1, enco_buf)) != '\0') {
if (c) {
if ((c = getbit(8, enco_buf)) == '\0') break;
fputc(c, outfile);
buffer[r++] = c; r &= (N - 1);
} else {
if ((i = getbit(EI, enco_buf)) == '\0') break;
if ((j = getbit(EJ, enco_buf)) == '\0') break;
for (k = 0; k <= j + 1; k++) {
c = buffer[(i + k) & (N - 1)];
fputc(c, outfile);
buffer[r++] = c; r &= (N - 1);
}
}
}
fclose(outfile);
}
Rather than taking the input from file, I am taking an encoded buffer which I am passing to the function decode() which in-turns passes to getbit(). But it is decoding upto a certain number of bits ie. 43. What I am guessing is I put '\0' instead of EOF (as it was in file end marker) to detect string end. and that might be the problem where break statement is executed finding '\0'. It might not be true but It might be the case. The encoding part has no problem as I verified it with the original code. Can anyone suggest where might be the problem?
EDIT : source code:
/* LZSS encoder-decoder (Haruhiko Okumura; public domain) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "lzss_lib.h"
#define EI 11 /* typically 10..13 */
#define EJ 4 /* typically 4..5 */
#define P 1 /* If match length <= P then output one character */
#define N (1 << EI) /* buffer size */
#define F ((1 << EJ) + 1) /* lookahead buffer size */
int bit_buffer = 0, bit_mask = 128;
unsigned long codecount = 0, textcount = 0;
unsigned char buffer[N * 2];
int payload_i = 0;
int enc_i = 0;
FILE *infile, *outfile;
void error(void)
{
printf("Output error\n"); exit(1);
}
void putbit1(unsigned char *put_buf0)
{
bit_buffer |= bit_mask;
if ((bit_mask >>= 1) == 0) {
put_buf0[payload_i] = bit_buffer;
payload_i++;
bit_buffer = 0; bit_mask = 128; codecount++;
}
}
void putbit0(unsigned char *put_buf1)
{
if ((bit_mask >>= 1) == 0) {
put_buf1[payload_i] = bit_buffer;
payload_i++;
bit_buffer = 0; bit_mask = 128; codecount++;
}
}
void flush_bit_buffer(unsigned char *flush_bit)
{
if (bit_mask != 128) {
flush_bit[payload_i] = bit_buffer;
codecount++;
}
}
void output1(int c, unsigned char *buf_output1)
{
int mask;
putbit1(buf_output1);
mask = 256;
while (mask >>= 1) {
if (c & mask) putbit1(buf_output1);
else putbit0(buf_output1);
}
}
void output2(int x, int y, unsigned char *buf_output2)
{
int mask;
putbit0(buf_output2);
mask = N;
while (mask >>= 1) {
if (x & mask) putbit1(buf_output2);
else putbit0(buf_output2);
}
mask = (1 << EJ);
while (mask >>= 1) {
if (y & mask) putbit1(buf_output2);
else putbit0(buf_output2);
}
}
void encode(unsigned char *string_buf, unsigned char *out_buf, unsigned long *out_buf_len)
{
int i, j, f1, x, y, r, s, bufferend, c, tt;
tt = 0;
for (i = 0; i < N - F; i++) buffer[i] = ' ';
for (i = N - F; i < N * 2; i++) {
if((c = string_buf[tt]) == '\0') break;
buffer[i] = c; textcount++; tt++;
}
bufferend = i; r = N - F; s = 0;
while (r < bufferend) {
f1 = (F <= bufferend - r) ? F : bufferend - r;
x = 0; y = 1; c = buffer[r];
for (i = r - 1; i >= s; i--)
if (buffer[i] == c) {
for (j = 1; j < f1; j++)
if (buffer[i + j] != buffer[r + j]) break;
if (j > y) {
x = i; y = j;
}
}
if (y <= P) { y = 1; output1(c, out_buf); }
else output2(x & (N - 1), y - 2, out_buf);
r += y; s += y;
if (r >= N * 2 - F) {
for (i = 0; i < N; i++) buffer[i] = buffer[i + N];
bufferend -= N; r -= N; s -= N;
while (bufferend < N * 2) {
if((c = string_buf[tt]) == '\0') break;
buffer[bufferend++] = c; textcount++; tt++;
}
}
}
flush_bit_buffer(out_buf);
*out_buf_len = codecount;
printf("text: %ld bytes\n", textcount);
printf("code: %ld bytes (%ld%%)\n", codecount, (codecount * 100) / textcount);
}
int getbit(int n, unsigned char *enco_buf) /* get n bits */
{
int i, x;
static int buf, mask = 0;
x = 0;
for (i = 0; i < n; i++) {
if (mask == 0) {
//if ((buf = fgetc(infile)) == EOF) return EOF;
//if ((buf = fgetc(infile)) == EOF) return EOF;
if((buf = enco_buf[enc_i]) == '\0') break;
//buf = enco_buf[enc_i];
enc_i++;
printf("\nValue of enc : %d\n", enc_i);
mask = 128;
}
x <<= 1;
if (buf & mask) x++;
mask >>= 1;
}
return x;
}
void decode(unsigned char *enco_buf)
{
int i, j, k, r, c;
outfile = fopen ("test_lib.txt", "wb");
for (i = 0; i < N - F; i++) buffer[i] = ' ';
r = N - F;
while ((c = getbit(1, enco_buf)) != '\0') {
if (c) {
if ((c = getbit(8, enco_buf)) == '\0') break;
fputc(c, outfile);
buffer[r++] = c; r &= (N - 1);
} else {
if ((i = getbit(EI, enco_buf)) == '\0') break;
if ((j = getbit(EJ, enco_buf)) == '\0') break;
for (k = 0; k <= j + 1; k++) {
c = buffer[(i + k) & (N - 1)];
fputc(c, outfile);
buffer[r++] = c; r &= (N - 1);
}
}
}
fclose(outfile);
}
and the test example :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "lzss_lib.h"
unsigned char compr_data[4096];
unsigned long pw = 0;
unsigned long payload_len = 0;
volatile int errno;
unsigned char *unc_data = "d(2306):AuthorisationScheme:RADIUSserveratfd04:bd3:80e8:1::1usingPAPD/6LoWPANd(2306):WritingModule:SecurityConfigD/6LoWPANd(2306):WritingModule:RunCoordinatorD/6LoWPANd(2306):RequestingmoduleaddressD/6LoWPANd(2306):WritingModule:GetAddressD/smartcard-jni(2781):SmartCard_state_update_callback:status=6D/SmartCardNative(2781):status=6D/smartcard(2781):PN532Smartcard_loop_threadexitD/smartcard-jni(2781):SmartCard_loop_thread:SMARTCARD_STATUS_ABORTD/smartcard(2781):Smartcard_loop_uninitD/smartcard(2781):2D/serialcomm_pn532(2781):PN532:Readingfrom/dev/ttyUSB0-->D/smartcard(2781):Received(0x3)fromPN532:(dataBuf[0]:0x1)(0x1f5988)D/smartcard(2781):ReceivedStatusfromPN532:OK(cmd:0x2)D/smartcard-jni(2781):SmartCard_listener_update_callbackD/smartcard(2781):Received(0x1c2)fromPN532:(dataBuf[0]:0x32)(0x1f5988)D/smartcard(2781):vd(2306):AuthorisationScheme:RADIUSserveratfd04:bd3:80e8:1::1usingPAPD/6LoWPANd(2306):";
FILE *outfile;
int main(void) {
memset (compr_data, '\0', sizeof(compr_data));
encode(unc_data, compr_data, &payload_len);
decode(compr_data);
return 0;
}
My file input contains the chars "abc" and is supposed to generate the hash: "a9993e364706816aba3e25717850c26c9cd0d89d" Instead, my output is 2474716729 148412417 414899454 2419217526 3285377520. My bit shifting should be correct but when I print out my W[t] I'm pretty sure the numbers are wrong.
#include <stdio.h>
#define MAX_SIZE 1048576
static unsigned char buffer[MAX_SIZE];
static unsigned int message[MAX_SIZE];
unsigned int readFile(unsigned char buffer[])
{
size_t length = 0;
int b = 0;
for (b = 0; b < MAX_SIZE; b++)
{
buffer[b]= '\0';
}
int i = 0;
char *fileName = "abc.txt";
FILE *filePointer = fopen(fileName, "r");
if (filePointer != NULL)
{
length = fread(buffer, sizeof(char), MAX_SIZE, filePointer);
if (ferror(filePointer)!= 0)
{
fputs("Error", stderr);
}
if (length > MAX_SIZE)
{
fputs("Input file too big for program", stderr);
}
//add one bit;
buffer[length] = 0x80;
//length++;
}
/*for (i = 0; i < MAX_SIZE; i++)
{
printf("%c", buffer[i]);
}
*/
fclose(filePointer);
return length;
}
unsigned int calculateBlocks(unsigned int sizeOfFileInBytes)
{
int blockCount = (((8 * sizeOfFileInBytes) + 1) / 512) + 1;
if((((8 * sizeOfFileInBytes) + 1) % 512) > (512 - 64))
{
blockCount = blockCount + 1;
}
//printf("here's block count: %i", blockCount);
return blockCount;
}
void convertCharArrayToIntArray(unsigned char buffer[], unsigned int
message[], unsigned int sizeOfFileInBytes)
{
int e = 0;
int d = 0;
//buffLength shows me how many chars are in array
size_t buffLength= strlen((char*)buffer);
//printf("this is bufflength: %zu -done", buffLength);
buffLength = buffLength/4;
for (e=0 ; e< buffLength; e++)
{
message[e] |= (buffer[e] <<24);
message[e] |= (buffer[e+1] <<16);
message[e] |= (buffer[e+2] <<8);
message[e] |= (buffer[e+3]);
}
/*for (d = 0; d <MAX_SIZE; d++)
{
printf("%i", message[d]);
} */
//printf("- done with message[d]");
}
void addBitCountToLastBlock(unsigned int message[], unsigned int
sizeOfFileInBytes, unsigned int blockCount)
{
int indexOfEndOfLastBlock = blockCount* 16 -1;
//printf("the size of file in bytes is: %i -done",
sizeOfFileInBytes);
sizeOfFileInBytes = sizeOfFileInBytes * 8;
message[indexOfEndOfLastBlock] = sizeOfFileInBytes;
//printf("index of last block is %i", message[indexOfEndOfLastBlock]);
int d = 0;
/* for (d = 0; d <MAX_SIZE; d++)
{
printf("%i", message[d]);
}
printf("- done with message[d]"); */
}
unsigned int K(unsigned int t)
{
unsigned int kHex[] = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6};
if (t>= 0 && t <= 19)
{
return kHex[0];
}
else if (t>= 20 && t <= 39)
{
return kHex[1];
}
else if (t>= 40 && t <= 59)
{
return kHex[2];
}
else if (t>= 60 && t <= 79)
{
return kHex[3];
}
return 0;
}
unsigned int f(unsigned int t, unsigned int B, unsigned int C, unsigned
int D)
{
if (t>= 0 && t <= 19)
{
return (B & C) |((~B)&D);
}
else if (t>= 20 && t <= 39)
{
return B^C^D;
}
else if (t>= 40 && t <= 59)
{
return (B & C) | (B & D) | (C & D);
}
else if (t>= 60 && t <= 79)
{
return B^C^D;
}
return 0 ;
}
void computeMessageDigest(unsigned int message[], unsigned int
blockCount)
void computeMessageDigest(unsigned int message[], unsigned int
blockCount)
{
unsigned int A, B, C, D, E;
unsigned int h[5];
unsigned int W[80];
unsigned int t = 0;
unsigned int temp; //temporary word value
unsigned int bCounter = 0;
int i = 0;
int d = 0 ;
// int z = 0;
//int blCount = 0;
/* for (d = 0; d <MAX_SIZE; d++)
{
printf("%i", message[d]);
}
printf("- done with message[d]"); */
int wInc = 0;
h[0] = 0x67452301;
h[1] = 0xefcdab89;
h[2] = 0x98badcfe;
h[3] = 0x10325476;
h[4] = 0xc3d2e1f0;
while ( bCounter < blockCount)
{
for (i= 16 * bCounter; i < 16 *bCounter +16; i++)
{
W[wInc] = message[i];
wInc++; //block one
}
wInc = 0;
/*for (z = 0; z < 16; z++)
{
printf("%i", W[z]);
} */
for (t = 16; t < 80; t++)
{
W[t] = (W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]) << 1;
// printf("%u ", W[t]);
}
A = h[0];
B = h[1];
C = h[2];
D = h[3];
E = h[4];
for (t = 0; t < 80; t++)
{
temp = (A << 5) + f(t, B, C, D) + E + W[t] + K(t);
E = D;
D = C;
C = B << 30;
B = A;
A = temp;
}
printf("Hex values for A, B, C, D, E");
printf("%u, %u, %u, %u, %u", A, B, C, D, E) ;
h[0] += A;
h[1] += B;
h[2] += C;
h[3] += D;
h[4] += E;
int b = 0;
for (b = 0; b <5; b++)
printf("%u ", h[b]);
bCounter++;
}
int main(int argc, const char * argv[]) {
// insert code here...
unsigned int blockCount = 0;
unsigned int sizeOfFile = 0;
sizeOfFile = readFile(buffer);
/*for (i = 0; i < MAX_SIZE; i++)
{
printf("%c", buffer[i]);
} */
//printf("%i is the size", readFile(buffer));
blockCount = calculateBlocks(sizeOfFile);
convertCharArrayToIntArray(buffer, message, sizeOfFile);
//printf("\n");
addBitCountToLastBlock(message, sizeOfFile, blockCount);
computeMessageDigest(message, blockCount);
return 0;
I am trying to input basic ip address from the user, but my command gets stuck here in the scanf and nothing after that is executed.
int ip1,ip2,ip3,ip4;
scanf("%d.%d.%d.%d",&ip1,&ip2,&ip3,&ip4);
printf("Here");
So, basically "Here" is never printed and the command scanf never gets over?
#include <stdio.h>
#include<math.h>
int main(void) {
char input;
char rep = 'r';
char quit = 'q';
char first = '1';
char second = '2';
input = rep;
while( input != quit) {
printf("What type of conversion do you want? \n");
printf("Enter 1 for 32-bit number to dot-decimal conversion, 2 for the inverse of operation: ");
char val;
scanf(" %c", &val);
if( val == first) {
} else if( val == second) {
printf("\nEnter dot-decimal IP address:");
int ip1,ip2,ip3,ip4;
scanf(" %d.%d.%d.%d", &ip1,&ip2,&ip3,&ip4);
printf("Here");
unsigned int ip = 0,c,k,counter = 31;
for(c = 7; c >= 0; c--) {
k = ip1 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
for(c = 7; c >= 0; c--) {
k = ip2 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
for(c = 7; c >= 0; c--) {
k = ip3 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
for(c = 7; c >= 0; c--) {
k = ip4 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
printf("%u is the IP Address",ip);
}
printf("\n \n Enter r to repeat, q to quit:");
scanf(" %c",&input);
}
return 0;
}
This is the exactly what i was doing. It gets stuck on when i try to get the IP Address in decimal notation.
I have analyzed your code after update (full code) and found that problem not in the input with scanf but in the for loops that are executed after data is obtained.
Look at that loop:
unsigned int ip = 0,c,k,counter = 31;
for(c = 7; c >= 0; c--) {
k = ip1 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
and particularly at for(c = 7; c >= 0; c--) taking into account that c is of type unsigned int... I see that this loop is INFINITE because decrement makes from 0 new positive value UINT_MAX (see limits.h).
I'm new in c programming and i'm trying to make a palindrome game. I've given the code below but there is some mistake I'm making and doesn't run can you please give me a hand. Thank you.
The point of the game is to give number to an array, then change with the keys a,d,x,w and try to make it palindrome.
If there is any error can u please give me some advice ?
This is pal.c
#include <stdio.h>
#include "visible.h"
//--------------------------------------------------
// is_pal
//--------------------------------------------------
void print_status(int a[], int* p, int num_mov);
int is_pal(int a[])
{
int b[6];
int i, j;
j = 0;
for (i = 5; i >= 0; i--)
{
b[j] = a[i];
j++;
}
for (i = 0; i <= 5; i++)
{
if (a[i] != b[i]) {
return 0;
}
}
return 1;
}
//--------------------------------------------------
// process_movement
//--------------------------------------------------
void process_movement(int a[], int* p, int num_mov, char c)
{
char d;
d=c;
if(d == 'd')
{
p = a+1;
num_mov++;
print_status(a,p,num_mov);
}
else if(d == 'a')
{
p = a-1;
num_mov++;
print_status(a,p,num_mov);
}
else if(d == 'x')
{
p = malloc(6*sizeof(int));
a = p-1;
num_mov++;
}
else if(d == 'w')
{
p = malloc(6*sizeof(int));
a = p+1;
num_mov++;
}
}
//--------------------------------------------------
// print_status
//--------------------------------------------------
void print_status(int a[], int* p, int num_mov)
{
printf("Number = ");
int i;
for( i = 0; i < 6; i++)
{
printf("%d ", a[i]);
}
printf("\n Number moves = ");
printf("%d", num_mov);
//printf("\n ","%s%", "Pointer is at position ");
printf("%d", *p);
printf("\n");
}
void user_game_palindrome(int pal_num)
{
int a[5];
int i,num_mov;
num_mov = 0;
i = 5;
while (pal_num != 0) {
a[i] = pal_num % 10;
pal_num = pal_num / 10;
i--;
}
int *p = a;
while (is_pal(a) == 1)
{
char c;
print_status(a,p,num_mov);
c = ask_for_command();
process_movement(a,p,num_mov,c);
}
}
This is ex1.c
#include "pal.h"
int main() {
int pal_num = 123342;
user_game_palindrome(pal_num);
return 0;
}
visible.c
#include "visible.h"
#include "conio.h"
//--------------------------------------------------
// gen_num
//--------------------------------------------------
int gen_num(int lb, int ub) {
int num = (rand() % (ub - lb)) + lb;
return num;
}
/* Note: Do not forget to include the following instruction at the beginning of your main() method:
srand(time(NULL));
*/
//--------------------------------------------------
// my_getchar
//--------------------------------------------------
char my_get_char() {
char my_char;
int b = 0;
char dummy_char;
my_char = getchar();
while (b == 0) {
dummy_char = getchar();
if (dummy_char == '\n')
b = 1;
}
return my_char;
}
this is the visible.c ( my teacher told me to include it)
Your conversion from int to array is wrong
for (i = 0; i < 4; i++) {
a[i] = pal_num%10;
pal_num = pal_num % 10;
}
Here, why would this loop end when i is 4. It should go till pal_num is 0. And pal_num = pal_num % 10; should be pal_num = pal_num / 10;
Try something like
i = 0;
while (pal_num != 0) {
a[i] = pal_num % 10;
pal_num = pal_num / 10;
i++;
}
NOTE: Be aware, that this would essentially reverse your int and store in the array.
There's a lot going wrong in your code and you still haven't fixed many things which have been pointed out by others.
as to remove the unnecessary creating of the array b, is_pal can be defined as:
int is_pal(int a[])
{
int i;
for (i = 0; i < 3; ++i)
{
if (a[5-i] != a[i])
return 0;
}
return 1;
}
process_movement doesn't have a case where d == 'w'
user_game_palindrome should have the while loop checking (is_pal(a) == 0)
And you should apply the changes that were suggested by #Haris
I need to convert the string "12345678" to the value 00010010001101000101011001111000 (the value in binary only without the zeroes on the left).
So I have written this code in c, the problem is that when I run it does nothing, just waits like there is an error until I stop it manually.
Any ideas?
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[4], result[4*strlen(string)];
for (i=0; i<strlen(string); i++) {
num = atoi(string[i]);
while (num != 0) {
arr[j++] = num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = 0;
tmp--;
}
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k++] = arr[j--];
}
j = 0;
tmp = 4;
}
printf("The result is: \n");
for (i=0; i<4*strlen(result); i++) {
printf("%d",result[i]);
}
printf("\n");
}
int main() {
char c[8] = "12345678";
reduce(c);
return 0;
}
Lots of small errors in your code, which makes it hard to pin-point a single error. Main problem seems to be you are confusing binary numbers (0, 1) with ASCII digits ("0", "1") and are mis-using string functions.
as mentioned elsewhere, char c[8] = .. is wrong.
atoi(string[i]) cannot work; it expects a string, not a char. Use `num = string[i]-'0';
arr[..] gets the value 'num%2, that is, a numerical value. Better to use '0'+num%2 so it's a character string.
you increment k in result[k++] inside a loop that already increments k
add result[k] = 0; at the end before printing, so strlen works correctly
4*strlen(result) is way too much -- the strlen is what it is.
you might as well do a simple printf("%s\n", result);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[5], result[4*strlen(string)+1];
for (i=0; i<strlen(string); i++) {
num = string[i]-'0';
while (num != 0) {
arr[j++] = '0'+num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = '0';
tmp--;
}
arr[j] = 0;
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k] = arr[j--];
}
j = 0;
tmp = 4;
}
result[k] = 0;
printf("The result is: \n");
for (i=0; i<strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
}
int main() {
char c[] = "12345678";
reduce(c);
return 0;
}
.. resulting in
The result is:
00010010001101000101011001111000
It seems from your example that the conversion you are attempting is to binary coded decimal rather than binary. That being the case your solution is somewhat over-complicated; you simply need to convert each digit to its integer value then translate the bit pattern to ASCII 1's and 0's.
#include <stdio.h>
void reduce( const char* c )
{
for( int d = 0; c[d] != 0; d++ )
{
int ci = c[d] - '0' ;
for( unsigned mask = 0x8; mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
}
On the other hand if you did intend a conversion to binary (rather than BCD), then if the entire string is converted to an integer, you can directly translate the bit pattern to ASCII 1's and 0's as follows:
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
void reduce( const char* c )
{
unsigned ci = (unsigned)atoi( c ) ;
static const int BITS = sizeof(ci) * CHAR_BIT ;
for( unsigned mask = 0x01 << (BITS - 1); mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
In your main(), do either
char c[ ] = "12345678";
or
char c[9] = "12345678";
if you want to use c as a string. Otherwise, it does not have enough space to store the terminating null character.
Here, I took the liberty to modify the code accordingly to work for you. Check the below code. Hope it's self-explanatoty.
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, count = 0; //count added, tmp removed
char arr[4], result[ (4*strlen(string) )+ 1], c; //1 more byte space to hold null
for (i=0; i<strlen(string); i++) {
c = string[i];
count = 4;
while (count != 0) { //constant iteration 4 times baed on 9 = 1001
arr[j++] = '0' + (c%2); //to store ASCII 0 or 1 [48/ 49]
c = c/2;
count--;
}
/* //not required
while (tmp >= 0) {
arr[j++] = 0;
tmp--;
}
*/
j--;
for (k=(i*4); k<((i*4) +4); k++) {
result[k] = arr[j--];
}
j = 0;
memset (arr, 0, sizeof(arr));
}
result[k] = 0;
printf("The result is: %s\n", result); //why to loop when we've added the terminating null? print directly.
/*
for (i=0; i< strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
*/
}
int main() {
char c[ ] = "12345678";
reduce(c);
return 0;
}
Output:
[sourav#broadsword temp]$ ./a.out
The result is: 00010010001101000101011001111000
Convert your string to an integer using int num = atoi(c).
Then do
int binary[50];
int q = num,i=0;
while(q != 0)
{
binary[i++] = q%2;
q = q/2;
}
Printing your binary array is reverse order will have your binary equivalent.
Full program:
#include<stdio.h>
int main(){
char c[100];
int num,q;
int binary[100],i=0,j;
scanf("%d",c);
num = atoi(c);
q = num;
while(q!=0){
binary[i++]= q % 2;
q = q / 2;
}
for(j = i -1 ;j>= 0;j--)
printf("%d",binary[j]);
return 0;
}
You can use the below reduce function.
void reduce(char string[])
{
unsigned int in = atoi(string) ;
int i = 0, result[32],k,j;
while (in > 0) {
j = in % 10;
k = 0;
while (j > 0) {
result[i++] = j % 2;
j = j >> 1;
k++;
}
while (k < 4) {
result[i++] = 0;
k++;
}
in = in/10;
}
printf("Result\n");
for(--i;i >= 0; i--) {
printf("%d", result[i]);
}
printf("\n");
}
For 12345678
the output would be 00010010001101000101011001111000, where each character is printed in its binary format.
It might need some adjustments, but it does the job as it is.
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int i;
int n;
char *str = "12345678";
const int bit = 1 << (sizeof(n)*8 - 1);
n = atoi(str);
for(i=0; i < sizeof(n)*8 ; i++, n <<= 1)
n&bit ? printf("1") : printf("0");
return 0;
}