I have a problem to convert from unsigned char into long.
The mission: I have 25 in (unsigned char) ptr->studentArr[i].subjectStatus when i = 0, I go into the function unsigned char fromDecToBinary(unsigned char tmpSubjectStatus), and I want in that function to get unsigned long 11001 into variable ret and then fprintf it into output.txt file.
Expectation: to fprintf into the file 11001 when i = 0, problem: it prints 25 instead(if I use fromDecToBinary function, it prints 0).
Please, just look at the 2 functions: outPutStudents and fromDecToBinary, other functions work properly, and those other functions just get the information and store the info. into structures which are then used to print the details into output.txt, most of them work, except the binary thingy.
input.txt file:
Nir 32251 99.80 11001
Ely 12347 77.89 01111
Moshe 45321 50.34 11111
Avi 31456 49.78 00011
*NOTE: this is the output without using the function fromDecToBinary
output.txt file:
Student 1: Nir 32251 99.80 25
Student 2: Ely 12347 77.89 15
Student 3: Moshe 45321 50.34 31
Student 4: Avi 31456 49.78 3
Code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct Student{
char* studentName; //Dyn. alloc. of stud. name
long id; // ID Number
float mark; // mark
unsigned char subjectStatus;
}Student;
typedef struct University{
Student* studentArr; // Dync. Alloc(Realloc) of students
int numOfStudents; //num of students
}University;
void getStudents(University *ptr);
unsigned char stringToBinary(unsigned char tmpSubjectStatus[]);
void outPutStudents(University *ptr);
unsigned char fromDecToBinary(University *ptr);
void main()
{
printf("Please enter details of student: (a)");
University uni;
getStudents(&uni); //Send address of structure University, because we want to change it not make a local copy of it
outPutStudents(&uni);
getch();
}
void getStudents(University *ptr)
{
FILE *op;
char tmpStudentName[20];
long tmpId;
float tmpMark;
char tmpSubjectStatus[6];
ptr->numOfStudents = 0;
if ((op = fopen("input.txt", "r")) == NULL)
{
printf("Failed to open file.");
}
ptr->studentArr = (Student*)malloc(sizeof(Student));
if (ptr->studentArr == NULL){
printf("Error: memory was not allocated.");
exit(1);
}
while (fscanf(op, "%s %ld %f %s", tmpStudentName, &tmpId, &tmpMark, tmpSubjectStatus) == 4)
{
ptr->numOfStudents++;
ptr->studentArr = (Student*)realloc(ptr->studentArr, sizeof(Student) * ptr->numOfStudents); /*Additional code for Realloc fails - we didn't study!*/
ptr->studentArr[ptr->numOfStudents - 1].studentName = (char*)malloc(sizeof(char)* strlen(tmpStudentName));
if (!(ptr->studentArr[ptr->numOfStudents - 1].studentName)) //if we failed to allocate memory for studentName
{
while (ptr->numOfStudents > 0)
{
free(ptr->studentArr[ptr->numOfStudents - 1].studentName); //free student name
ptr->numOfStudents--; // decrease numOfStudents by one
}
free(ptr->studentArr); //if all student names are free, we need to free the array
printf("Student name was not allocated.");
exit(1);
}
strcpy(ptr->studentArr[ptr->numOfStudents - 1].studentName, tmpStudentName);
ptr->studentArr[ptr->numOfStudents - 1].id = tmpId;
ptr->studentArr[ptr->numOfStudents - 1].mark = tmpMark;
ptr->studentArr[ptr->numOfStudents - 1].subjectStatus = stringToBinary(tmpSubjectStatus); //atoi: from "11001"(string) to 11001(int),then casting to unsigned char
}
fclose(op);
}
void outPutStudents(University *ptr)
{
int i;
FILE *fp;
unsigned char tmpSubjectStatus;
long val;
if ((fp = fopen("output.txt", "w")) == NULL)
{
printf("Couldn't open output file.");
exit(1);
}
for (i = 0; ptr->numOfStudents != i; i++){
tmpSubjectStatus = ptr->studentArr[i].subjectStatus;
val = fromDecToBinary(tmpSubjectStatus);
fprintf(fp, "Student %d: %s %ld %.2f %ld \n", i + 1, ptr->studentArr[i].studentName, ptr->studentArr[i].id, ptr->studentArr[i].mark, tmpSubjectStatus);
}
fclose(fp);
}
unsigned char stringToBinary(char tmpSubjectStatus[])
{
unsigned char tmpBinaryCh = 0;
int i;
for (i = 0; i < 5; i++){
if (tmpSubjectStatus[i] == '1') tmpBinaryCh += 1 << (4 - i);
}
return tmpBinaryCh;
}
unsigned char fromDecToBinary(unsigned char tmpSubjectStatus)
{
int i;
long ret;
char arrBinary[6];
for (i = 0; i < 5; i++){
arrBinary[4 - i] = tmpSubjectStatus % 2;
tmpSubjectStatus /= 2;
}
arrBinary[5] = '/0';
ret = strtol(arrBinary, NULL, 10);
return ret;
}
You have several errors in the fromDecToBinary function:
Replace the '/0' with '\0'.
Store '0' + tmpSubjectStatus % 2 in the array.
Add proper error handling to the strtol call.
Change the return type to long.
If you want to print some binary using numbers use this.
#include <stdio.h>
#include <stdlib.h>
void print_bin(uint64_t num, size_t bytes) {
int i = 0;
for(i = bytes * 8; i > 0; i--) {
(i % 8 == 0) ? printf("|") : 1;
(num & 1) ? printf("1") : printf("0");
num >>= 1;
}
printf("\n");
}
int main(void) {
int arg = atoi("25");
print_bin(arg, 1);
return 0;
}
It also prints a vertical bar every 8 bits to make the bytes easier to read but you can just remove that.
If you want to specify how many bytes you want use this
#include <stdio.h>
#include <stdlib.h>
void print_bin(uint64_t num, size_t bytes) {
int i = 0;
for(i = bytes * 8; i > 0; i--) {
(i % 8 == 0) ? printf("|") : 1;
(num & 1) ? printf("1") : printf("0");
num >>= 1;
}
printf("\n");
}
int main(void) {
print_bin(16000, 3);
return 0;
}
#include <stdio.h>
int main()
{
unsigned char tmpSubjectStatus=25;
long quotient = tmpSubjectStatus;
long remainder;
long binary=0;
long multiplier=1;
while(quotient!=0){
remainder=quotient % 2;
binary=binary+(remainder*multiplier);
multiplier=multiplier*10;
quotient = quotient / 2;
}
printf("%ld",binary);
return 0;
}
Try this.
In the function it will be like this
long fromDecToBinary(unsigned char tmpSubjectStatus)
{
long quotient = tmpSubjectStatus;
long remainder;
long binary=0;
long multiplier=1;
while(quotient!=0){
remainder=quotient % 2;
binary=binary+(remainder*multiplier);
multiplier=multiplier*10;
quotient = quotient / 2;
}
return binary;
}
In here return type is changed to long.
Related
I have a 1 dimensional array in which ive initialized as 0 but for some reason when i go inside a loop and try to increase its contents by one the value at position 0 keeps reverting to 0 even after i increase it by 1.
#include <stdio.h>
#include <stdlib.h>
#define TOTAL_V 3
#define NUM_CANDIDATES 7
int hex_age(unsigned short hex){
unsigned short age = hex >> 9;
if (age >18 && age <101)
return age;
else return 0;
}
int hex_gender(unsigned short hex){
unsigned short gender = hex >> 7 & 3;
return gender;
}
int hex_vote(unsigned short hex){
unsigned short vote, tmp = hex & 0x7f , count = 0;
if (tmp == 0)
return 7;
for (int i = 0 ; i<7; i++){
if (tmp & 1 == 1){
count++;
vote = i;
}
tmp = tmp >> 1;
}
if (count > 1)
return 7;
return vote;
}
int main() {
int s_votes = 0, f_votes = 0, v_count[NUM_CANDIDATES] = {0};
unsigned short **v_info, hex_v_info , age , gender , vote;
FILE *fp;
fp = fopen("data1.dat" , "r");
if (fp == NULL){
fprintf(stderr ,"apotuxe o anoigmos tou arxeiou");
exit(-1);
}
if (feof(fp)){
fprintf(stderr, "to arxeio einai adeio");
exit(-1);
}
while (fscanf(fp ,"%x", &hex_v_info) != EOF){
age = hex_age(hex_v_info);
if(age == 0)
f_votes++;
else {
gender = hex_gender(hex_v_info);
if (gender == 0)
f_votes++;
else{
vote = hex_vote(hex_v_info);
if (vote == 7)
f_votes++;
else{
if (s_votes == 0){
v_info = malloc(sizeof(int *));
v_info[s_votes] =malloc(sizeof(int)* TOTAL_V);
}
else{
v_info = realloc(v_info , sizeof(int *)*(s_votes+1));
v_info[s_votes] = malloc(sizeof(int)*TOTAL_V);
}
v_info[s_votes][0] = age;
v_info[s_votes][1] = gender;
v_info[s_votes][2] = vote;
v_count[vote]++;
s_votes++;
}
}
}
}
fclose(fp);
for (int i = 0; i<s_votes; i++)
free(v_info);
return 0;
}
and for some reason when i use calloc to create the array it doesnt have that problem. Does anyone know why that happens
You declare unsigned short hex_v_info (2 bytes on my system), then read data from with fscanf(fp ,"%x", &hex_v_info) where the format string %x expect the address of an int (4 bytes on my system). This will certainly overwrite data unexpectedly.
unsigned short **v_info but you store an array of int [s_votes]. If your pointers are not uniform this will be a problem.
realloc(NULL, 1) is well defined so just use instead of malloc() of the first element. You need to assign the result of realloc()` to e temporary variable, however, to be able handle NULL. Otherwise you lose data & leak memory.
free(v_info); results in a double free if s_votes > 1, and you still leak the memory you allocate at v_info[i].
#include <stdio.h>
#include <stdlib.h>
#define TOTAL_V 3
#define NUM_CANDIDATES 7
// 0x1111 1110 0000 0000
int hex_age(unsigned short hex){
unsigned short age = hex >> 9;
if (age >18 && age < 101)
return age;
return 0;
}
// 0x0000 0001 1000 0000
int hex_gender(unsigned short hex){
unsigned short gender = hex >> 7 & 3; // bit 7 and 6
return gender;
}
// 0x0000 0000 0111 1111
int hex_vote(unsigned short hex){
unsigned short vote, tmp = hex & 0x7f , count = 0; // bit 11 through 0
if (tmp == 0)
return 7;
for (int i = 0 ; i<7; i++){
if ((tmp & 1) == 1){
count++;
vote = i;
}
tmp = tmp >> 1;
}
if (count > 1)
return 7;
return vote;
}
int main() {
int s_votes = 0, f_votes = 0, v_count[NUM_CANDIDATES] = {0};
unsigned short hex_v_info;
int **v_info = NULL;
FILE *fp = fopen("data1.dat" , "r");
if (!fp){
fprintf(stderr ,"apotuxe o anoigmos tou arxeiou");
exit(-1);
}
for(;;) {
int rv = fscanf(fp ,"%hx", &hex_v_info);
if(rv == EOF) break;
if(rv != 1) {
printf("err\n");
return 1;
}
unsigned short age = hex_age(hex_v_info);
if(!age) {
f_votes++;
continue;
}
unsigned short gender = hex_gender(hex_v_info);
if (!gender) {
f_votes++;
continue;
}
unsigned short vote = hex_vote(hex_v_info);
if (vote == 7) {
f_votes++;
continue;
}
int **tmp = realloc(v_info, sizeof *tmp * (s_votes + 1));
if(!tmp) {
// handle error: free v_info[i] and v_info?
return 1;
}
v_info = tmp;
v_info[s_votes] = malloc(sizeof **v_info * TOTAL_V);
v_info[s_votes][0] = age;
v_info[s_votes][1] = gender;
v_info[s_votes][2] = vote;
v_count[vote]++;
s_votes++;
}
fclose(fp);
printf("f_votes: %d\n", f_votes);
for(size_t i = 0; i < s_votes; i++) {
printf("%zu: %d %d %d\n",
i,
v_info[i][0],
v_info[i][1],
v_info[i][2]
);
}
for (int i = 0; i< s_votes; i++)
free(v_info[i]);
free(v_info);
return 0;
}
and with input file file:
a081
a082
it appears to process the info data correctly:
f_votes: 0
0: 80 1 0
1: 80 1 1
I'm trying to create anagrams from words where answers are supposed to be for example:
The word "at" should have two anagrams.
ordeals should have 5040 anagrams.
abcdABCDabcd shoud have 29937600 anagrams.
abcdefghijklmnopqrstuvwxyz should have 403291461126605635584000000 anagrams.
abcdefghijklmabcdefghijklm should have 49229914688306352000000.
My program seems to work for the first three examples but not for the last two. How can I change the program to make it work?
#include <stdio.h>
#include <memory.h>
int contains(char haystack[], char needle) {
size_t len = strlen(haystack);
int i;
for (i = 0; i < len; i++) {
if (haystack[i] == needle) {
return 1;
}
}
return 0;
}
unsigned long long int factorial(unsigned long long int f) {
if (f == 0)
return 1;
return (f * factorial(f - 1));
}
int main(void) {
char str[1000], ch;
unsigned long long int i;
unsigned long long int frequency = 0;
float answer = 0;
char visited[1000];
int indexvisited = 0;
printf("Enter a string: ");
scanf("%s", str);
for (i = 0; str[i] != '\0'; ++i);
unsigned long long int nominator = 1;
for (int j = 0; j < i; ++j) {
ch = str[j];
frequency = 0;
if (!contains(visited, ch)) {
for (int k = 0; str[k] != '\0'; ++k) {
if (ch == str[k])
++frequency;
}
printf("Frequency of %c = %lld\n", ch, frequency);
visited[indexvisited] = ch;
visited[++indexvisited] = '\0';
nominator = nominator * factorial(frequency);
}
}
printf("Number of anagrams = %llu\n", (factorial( i )/nominator ) );
return 0;
}
Even though an unsigned long long is pretty big, it's not completely unbounded. Its maximum value is around 1*10^19. If your source string is 26 characters long, you calculate factorial(26) - which is around 4*10^26, much much bigger than will fit in an unsigned long long.
When you need to work with ridicously large numbers you have to split things, i'd say that using a long double to store the root number and a long unsigned int to store the 10th potence would do the trick.
4*10^26 == ld 4, lui 26 == ld * 10^lui
this could be usefull for calculations, not sure tho how to represent it, it'll overflow everything but a string
Just for the fun, here's the best I could come up with using only built-in datatypes. Instead of calculating factorials over and over (and, btw, avoid recursion for such things!), it has an "intelligent" n over k function. Note that it attempts to detect an overflow, but this is not really reliable.
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef size_t AsciiCountTable[0x80];
static int countAsciiCharacters(const char *input, AsciiCountTable table)
{
const char *c = input;
while (*c)
{
if ((unsigned char)*c > 0x7f)
{
// not an ascii character
return 0;
}
++table[(int)*c];
++c;
}
return 1;
}
static unsigned long long nOverK(size_t n, size_t k)
{
unsigned long long result = 1;
size_t barrier = n - k;
if (k > barrier) barrier = k;
for (size_t i = n; i > barrier; --i)
{
result *= i;
}
for (size_t i = 2; i <= n - barrier; ++i)
{
result /= i;
}
return result;
}
int main(int argc, char **argv)
{
if (argc < 2)
{
fprintf(stderr, "Usage: %s <word>\n", argv[0]);
return EXIT_FAILURE;
}
AsciiCountTable countTable = {0};
if (!countAsciiCharacters(argv[1], countTable))
{
fputs("Only ASCII characters allowed.\n", stderr);
return EXIT_FAILURE;
}
size_t positions = strlen(argv[1]);
unsigned long long permutations = 1;
for (int i = 0; i < 0x80; ++i)
{
size_t n = positions;
size_t k = countTable[i];
if (k > 0)
{
unsigned long long temp = permutations;
permutations *= nOverK(n, k);
if (temp > permutations)
{
fputs("Overflow detected.\n", stderr);
return EXIT_FAILURE;
}
positions -= k;
}
}
printf("permutations: %" PRIuMAX "\n", permutations);
return EXIT_SUCCESS;
}
I'm trying to convert an ascii string to a binary string in C. I found this example Converting Ascii to binary in C but I rather not use a recursive function. I tried to write an iterative function as opposed to a recursive function, but the binary string is missing the leading digit. I'm using itoa to convert the string, however itoa is a non standard function so I used the implementation from What is the proper way of implementing a good "itoa()" function? , the one provided by Minh Nguyen.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int32_t ascii_to_binary(char *input, char **out, uint64_t len)
{
uint32_t i;
uint32_t str_len = len * 8;
if(len == 0)
{
printf("Length argument is zero\n");
return (-1);
}
(*out) = malloc(str_len + 1);
if((*out) == NULL)
{
printf("Can't allocate binary string: %s\n", strerror(errno));
return (-1);
}
if(memset((*out), 0, (str_len)) == NULL)
{
printf("Can't initialize memory to zero: %s\n", strerror(errno));
return (-1);
}
for(i = 0; i < len; i++)
itoa((int32_t)input[i], &(*out)[(i * 8)], 2);
(*out)[str_len] = '\0';
return (str_len);
}
int main(void)
{
int32_t rtrn = 0;
char *buffer = NULL;
rtrn = ascii_to_binary("a", &buffer, 1);
if(rtrn < 0)
{
printf("Can't convert string\n");
return (-1);
}
printf("str: %s\n", buffer);
return (0);
}
I get 1100001 for ascii character a, but I should get 01100001, so how do I convert the ascii string to the whole binary string?
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;
}
Best just write a simple function to do this using bitwise operators...
#define ON_BIT = 0x01
char *strToBin(char c) {
static char strOutput[10];
int bit;
/*Shifting bits to the right, but don't want the output to be in reverse
* so indexing bytes with this...
*/
int byte;
/* Add a nul at byte 9 to terminate. */
strOutput[8] = '\0';
for (bit = 0, byte = 7; bit < 8; bit++, byte--) {
/* Shifting the bits in c to the right, each time and'ing it with
* 0x01 (00000001).
*/
if ((c >> bit) & BIT_ON)
/* We know this is a 1. */
strOutput[byte] = '1';
else
strOutput[byte] = '0';
}
return strOutput;
}
Something like that should work, there's loads of ways you can do it. Hope this helps.
I am having trouble with a binary search on strings in c. I use the strcmp function to compare the strings, but I still get no output when I type in a name that I know is in the list.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LEN 25
void insert_sata(char **strings, const char* filename, int size);
void allocate( char ***strings, int size);
int binary_search(char **strings, char *target, int start_idx, int end_idx);
int main(int argc, char* argv[]){
if(argc != 4){
printf("Wrong number of args");
}
char **pointer;
int size = atoi(argv[1]);
allocate(&pointer, size);
insert_data(pointer, argv[2], size);
int x;
int z = 1;
char search_name[MAX_STRING_LEN];
while( z == 1){
printf("\nEnter a name to search for: ");
scanf("%s", search_name);
x = binary_search(pointer, search_name, 0, size);
printf("\nContinue searching names? ( 1 = yes, 0 = No):");
scanf("%d", &z);
}
}
void allocate(char ***strings, int size){
int i;
*strings = malloc(sizeof(**strings) * size);
for( i = 0; i < size; i++)
{
(*strings)[i] = malloc(sizeof(char) * MAX_STRING_LEN);
}
}
void insert_data(char **strings, const char* filename, int size){
FILE *input;
input = fopen(filename, "r");
int i;
for (i = 0; i < size; i++){
fscanf(input,"%24s", strings[i]);
}
fclose(input);
}
int binary_search(char **strings, char *target, int start_idx, int end_idx){
int result;
int mid_idx = 0;
while( end_idx >= start_idx){
mid_idx = (end_idx + start_idx) / 2;
result = strcmp(strings[mid_idx], target);
if(result > 0){
end_idx = start_idx - 1;
}
else if (result < 0){
start_idx = mid_idx + 1;
}
else if( result == 0){
printf("%s was found in the set", target);
}
}
}
The binary search is the function that is giving me trouble. I do not recieve any seg faults or anything, just nothing is displayed when I search a name that is in the file. Here is the list of names that I scan into the program.
matt
susan
mark
david
aden
phil
erik
john
caden
mycah
Your input list isn't sorted and your program doesn't seem to try to sort it. Suppose you look for 'susan' - first comparision is 'susan' to 'aden', and the search area gets narrowed to last 5 items, while 'susan' is at the second position......
This:
if (result > 0) {
end_idx = start_idx - 1;
}
is probably mean to be:
if (result > 0) {
end_idx = mid_idx - 1;
}
The binary search algorithm requires that the list is sorted. Your example list isn't, so the algorithm will not work
I'm looking for a function to allow me to print the binary representation of an int. What I have so far is;
char *int2bin(int a)
{
char *str,*tmp;
int cnt = 31;
str = (char *) malloc(33); /*32 + 1 , because its a 32 bit bin number*/
tmp = str;
while ( cnt > -1 ){
str[cnt]= '0';
cnt --;
}
cnt = 31;
while (a > 0){
if (a%2==1){
str[cnt] = '1';
}
cnt--;
a = a/2 ;
}
return tmp;
}
But when I call
printf("a %s",int2bin(aMask)) // aMask = 0xFF000000
I get output like;
0000000000000000000000000000000000xtpYy (And a bunch of unknown characters.
Is it a flaw in the function or am I printing the address of the character array or something? Sorry, I just can't see where I'm going wrong.
NB The code is from here
EDIT: It's not homework FYI, I'm trying to debug someone else's image manipulation routines in an unfamiliar language. If however it's been tagged as homework because it's an elementary concept then fair play.
Here's another option that is more optimized where you pass in your allocated buffer. Make sure it's the correct size.
// buffer must have length >= sizeof(int) + 1
// Write to the buffer backwards so that the binary representation
// is in the correct order i.e. the LSB is on the far right
// instead of the far left of the printed string
char *int2bin(int a, char *buffer, int buf_size) {
buffer += (buf_size - 1);
for (int i = 31; i >= 0; i--) {
*buffer-- = (a & 1) + '0';
a >>= 1;
}
return buffer;
}
#define BUF_SIZE 33
int main() {
char buffer[BUF_SIZE];
buffer[BUF_SIZE - 1] = '\0';
int2bin(0xFF000000, buffer, BUF_SIZE - 1);
printf("a = %s", buffer);
}
A few suggestions:
null-terminate your string
don't use magic numbers
check the return value of malloc()
don't cast the return value of malloc()
use binary operations instead of arithmetic ones as you're interested in the binary representation
there's no need for looping twice
Here's the code:
#include <stdlib.h>
#include <limits.h>
char * int2bin(int i)
{
size_t bits = sizeof(int) * CHAR_BIT;
char * str = malloc(bits + 1);
if(!str) return NULL;
str[bits] = 0;
// type punning because signed shift is implementation-defined
unsigned u = *(unsigned *)&i;
for(; bits--; u >>= 1)
str[bits] = u & 1 ? '1' : '0';
return str;
}
Your string isn't null-terminated. Make sure you add a '\0' character at the end of the string; or, you could allocate it with calloc instead of malloc, which will zero the memory that is returned to you.
By the way, there are other problems with this code:
As used, it allocates memory when you call it, leaving the caller responsible for free()ing the allocated string. You'll leak memory if you just call it in a printf call.
It makes two passes over the number, which is unnecessary. You can do everything in one loop.
Here's an alternative implementation you could use.
#include <stdlib.h>
#include <limits.h>
char *int2bin(unsigned n, char *buf)
{
#define BITS (sizeof(n) * CHAR_BIT)
static char static_buf[BITS + 1];
int i;
if (buf == NULL)
buf = static_buf;
for (i = BITS - 1; i >= 0; --i) {
buf[i] = (n & 1) ? '1' : '0';
n >>= 1;
}
buf[BITS] = '\0';
return buf;
#undef BITS
}
Usage:
printf("%s\n", int2bin(0xFF00000000, NULL));
The second parameter is a pointer to a buffer you want to store the result string in. If you don't have a buffer you can pass NULL and int2bin will write to a static buffer and return that to you. The advantage of this over the original implementation is that the caller doesn't have to worry about free()ing the string that gets returned.
A downside is that there's only one static buffer so subsequent calls will overwrite the results from previous calls. You couldn't save the results from multiple calls for later use. Also, it is not threadsafe, meaning if you call the function this way from different threads they could clobber each other's strings. If that's a possibility you'll need to pass in your own buffer instead of passing NULL, like so:
char str[33];
int2bin(0xDEADBEEF, str);
puts(str);
Here is a simple algorithm.
void decimalToBinary (int num) {
//Initialize mask
unsigned int mask = 0x80000000;
size_t bits = sizeof(num) * CHAR_BIT;
for (int count = 0 ;count < bits; count++) {
//print
(mask & num ) ? cout <<"1" : cout <<"0";
//shift one to the right
mask = mask >> 1;
}
}
this is what i made to display an interger as a binairy code it is separated per 4 bits:
int getal = 32; /** To determain the value of a bit 2^i , intergers are 32bits long**/
int binairy[getal]; /** A interger array to put the bits in **/
int i; /** Used in the for loop **/
for(i = 0; i < 32; i++)
{
binairy[i] = (integer >> (getal - i) - 1) & 1;
}
int a , counter = 0;
for(a = 0;a<32;a++)
{
if (counter == 4)
{
counter = 0;
printf(" ");
}
printf("%i", binairy[a]);
teller++;
}
it could be a bit big but i always write it in a way (i hope) that everyone can understand what is going on. hope this helped.
#include<stdio.h>
//#include<conio.h> // use this if you are running your code in visual c++, linux don't
// have this library. i have used it for getch() to hold the screen for input char.
void showbits(int);
int main()
{
int no;
printf("\nEnter number to convert in binary\n");
scanf("%d",&no);
showbits(no);
// getch(); // used to hold screen...
// keep code as it is if using gcc. if using windows uncomment #include & getch()
return 0;
}
void showbits(int n)
{
int i,k,andmask;
for(i=15;i>=0;i--)
{
andmask = 1 << i;
k = n & andmask;
k == 0 ? printf("0") : printf("1");
}
}
Just a enhance of the answer from #Adam Markowitz
To let the function support uint8 uint16 uint32 and uint64:
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
// Convert integer number to binary representation.
// The buffer must have bits bytes length.
void int2bin(uint64_t number, uint8_t *buffer, int bits) {
memset(buffer, '0', bits);
buffer += bits - 1;
for (int i = bits - 1; i >= 0; i--) {
*buffer-- = (number & 1) + '0';
number >>= 1;
}
}
int main(int argc, char *argv[]) {
char buffer[65];
buffer[8] = '\0';
int2bin(1234567890123, buffer, 8);
printf("1234567890123 in 8 bits: %s\n", buffer);
buffer[16] = '\0';
int2bin(1234567890123, buffer, 16);
printf("1234567890123 in 16 bits: %s\n", buffer);
buffer[32] = '\0';
int2bin(1234567890123, buffer, 32);
printf("1234567890123 in 32 bits: %s\n", buffer);
buffer[64] = '\0';
int2bin(1234567890123, buffer, 64);
printf("1234567890123 in 64 bits: %s\n", buffer);
return 0;
}
The output:
1234567890123 in 8 bits: 11001011
1234567890123 in 16 bits: 0000010011001011
1234567890123 in 32 bits: 01110001111110110000010011001011
1234567890123 in 64 bits: 0000000000000000000000010001111101110001111110110000010011001011
Two things:
Where do you put the NUL character? I can't see a place where '\0' is set.
Int is signed, and 0xFF000000 would be interpreted as a negative value. So while (a > 0) will be false immediately.
Aside: The malloc function inside is ugly. What about providing a buffer to int2bin?
A couple of things:
int f = 32;
int i = 1;
do{
str[--f] = i^a?'1':'0';
}while(i<<1);
It's highly platform dependent, but
maybe this idea above gets you started.
Why not use memset(str, 0, 33) to set
the whole char array to 0?
Don't forget to free()!!! the char*
array after your function call!
Two simple versions coded here (reproduced with mild reformatting).
#include <stdio.h>
/* Print n as a binary number */
void printbitssimple(int n)
{
unsigned int i;
i = 1<<(sizeof(n) * 8 - 1);
while (i > 0)
{
if (n & i)
printf("1");
else
printf("0");
i >>= 1;
}
}
/* Print n as a binary number */
void printbits(int n)
{
unsigned int i, step;
if (0 == n) /* For simplicity's sake, I treat 0 as a special case*/
{
printf("0000");
return;
}
i = 1<<(sizeof(n) * 8 - 1);
step = -1; /* Only print the relevant digits */
step >>= 4; /* In groups of 4 */
while (step >= n)
{
i >>= 4;
step >>= 4;
}
/* At this point, i is the smallest power of two larger or equal to n */
while (i > 0)
{
if (n & i)
printf("1");
else
printf("0");
i >>= 1;
}
}
int main(int argc, char *argv[])
{
int i;
for (i = 0; i < 32; ++i)
{
printf("%d = ", i);
//printbitssimple(i);
printbits(i);
printf("\n");
}
return 0;
}
//This is what i did when our teacher asked us to do this
int main (int argc, char *argv[]) {
int number, i, size, mask; // our input,the counter,sizeofint,out mask
size = sizeof(int);
mask = 1<<(size*8-1);
printf("Enter integer: ");
scanf("%d", &number);
printf("Integer is :\t%d 0x%X\n", number, number);
printf("Bin format :\t");
for(i=0 ; i<size*8 ;++i ) {
if ((i % 4 == 0) && (i != 0)) {
printf(" ");
}
printf("%u",number&mask ? 1 : 0);
number = number<<1;
}
printf("\n");
return (0);
}
the simplest way for me doing this (for a 8bit representation):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char *intToBinary(int z, int bit_length){
int div;
int counter = 0;
int counter_length = (int)pow(2, bit_length);
char *bin_str = calloc(bit_length, sizeof(char));
for (int i=counter_length; i > 1; i=i/2, counter++) {
div = z % i;
div = div / (i / 2);
sprintf(&bin_str[counter], "%i", div);
}
return bin_str;
}
int main(int argc, const char * argv[]) {
for (int i = 0; i < 256; i++) {
printf("%s\n", intToBinary(i, 8)); //8bit but you could do 16 bit as well
}
return 0;
}
Here is another solution that does not require a char *.
#include <stdio.h>
#include <stdlib.h>
void print_int(int i)
{
int j = -1;
while (++j < 32)
putchar(i & (1 << j) ? '1' : '0');
putchar('\n');
}
int main(void)
{
int i = -1;
while (i < 6)
print_int(i++);
return (0);
}
Or here for more readability:
#define GRN "\x1B[32;1m"
#define NRM "\x1B[0m"
void print_int(int i)
{
int j = -1;
while (++j < 32)
{
if (i & (1 << j))
printf(GRN "1");
else
printf(NRM "0");
}
putchar('\n');
}
And here is the output:
11111111111111111111111111111111
00000000000000000000000000000000
10000000000000000000000000000000
01000000000000000000000000000000
11000000000000000000000000000000
00100000000000000000000000000000
10100000000000000000000000000000
#include <stdio.h>
#define BITS_SIZE 8
void
int2Bin ( int a )
{
int i = BITS_SIZE - 1;
/*
* Tests each bit and prints; starts with
* the MSB
*/
for ( i; i >= 0; i-- )
{
( a & 1 << i ) ? printf ( "1" ) : printf ( "0" );
}
return;
}
int
main ()
{
int d = 5;
printf ( "Decinal: %d\n", d );
printf ( "Binary: " );
int2Bin ( d );
printf ( "\n" );
return 0;
}
Not so elegant, but accomplishes your goal and it is very easy to understand:
#include<stdio.h>
int binario(int x, int bits)
{
int matriz[bits];
int resto=0,i=0;
float rest =0.0 ;
for(int i=0;i<8;i++)
{
resto = x/2;
rest = x%2;
x = resto;
if (rest>0)
{
matriz[i]=1;
}
else matriz[i]=0;
}
for(int j=bits-1;j>=0;j--)
{
printf("%d",matriz[j]);
}
printf("\n");
}
int main()
{
int num,bits;
bits = 8;
for (int i = 0; i < 256; i++)
{
num = binario(i,bits);
}
return 0;
}
#include <stdio.h>
int main(void) {
int a,i,k=1;
int arr[32]; \\ taken an array of size 32
for(i=0;i <32;i++)
{
arr[i] = 0; \\initialised array elements to zero
}
printf("enter a number\n");
scanf("%d",&a); \\get input from the user
for(i = 0;i < 32 ;i++)
{
if(a&k) \\bit wise and operation
{
arr[i]=1;
}
else
{
arr[i]=0;
}
k = k<<1; \\left shift by one place evry time
}
for(i = 31 ;i >= 0;i--)
{
printf("%d",arr[i]); \\print the array in reverse
}
return 0;
}
void print_binary(int n) {
if (n == 0 || n ==1)
cout << n;
else {
print_binary(n >> 1);
cout << (n & 0x1);
}
}