Decimal to Binary conversion - c

I need to convert a 20digits decimal to binary using C programming. What buffer will I create, because it will be very large, even the calculator can't compute converting 20 digits to Binary.
here is sample of what i intend to accomplish:
Let is assume this code:
I am type this value via my keyboard into the buffer. Meanwhile, I am using an AT85C55WD Mcu.
unsigned char idata token[20]=(2,3,5,6,3,3,4,4,3,2,4,4,6,7,4,3,4,5,3,3);
I want a result
type-define variable convrt_token= 23562244324467434533;
Is this possible using C? If it is, then please how do i go about it?

each digit in decimal has 10 values, 0..9. so you'll need between 3 and 4 digits in binary. so let's say 4 to keep it simple.
so for a 20 digit decimal you'll need an 80 digit number in binary.
you can do it all with chars to keep it simple as well. i assume this is for fun.
char decnum[20];
char binnum[80];
good luck.

Here is elegent solution....:)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<unistd.h>
#include<assert.h>
#include<stdbool.h>
#define max 10000
#define RLC(num,pos) ((num << pos)|(num >> (32 - pos)))
#define RRC(num,pos) ((num >> pos)|(num << (32 - pos)))
void tobinstr(int value, int bitsCount, char* output)
{
int i;
output[bitsCount] = '\0';
for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
int main()
{
char s[50];
tobinstr(65536,32, s);
printf("%s\n", s);
return 0;
}

Start off as Gidon mentions. Then you only need to define a function 'decToBin' or something like that, which you can use like this:
char decnum[20];
char binnum[80];
// ... get the values, do zero initialization etc...
decToBin( decnum, binnum );
And you're ready to go.
The decToBin function could easily be implemented as a common long division algorithm. That shouldn't be too hard.
Have fun ;)
EDIT: Detailed description:
Look at your last digit. Is it divisible by 2?
--> yes: your binary digit will be 0
--> no: your binary digit will be 1
Divide the entire decimal number by 2 (Long division preferrably) and truncate if necessary.
start over. You will get the binary digits in reverse order. (Repeat until your decimal number is 0)

Related

Converting Decimal to Binary with long integer values C

My program is meant to convert decimal to binary by reading values from an input file and then outputting the binary values into an output file. Lets say the input file has these numbers:
190 31 5 891717742
Everything converts to binary just fine except for the 891717742. This outputs a value which is completely off of the binary output. Ive tried a LONG but they just output a negative value. For example this would output:
11000100 11110010 11 "1434923237" <- not right (not the actual binary values)
Decimal to Binary (from online):
char* convertDecimalToBinary(int n)
{
int binaryNumber = 0;
int remainder, i = 1;
static char buff[100];
while (n!=0)
{
remainder = n%2;
n /= 2;
binaryNumber += remainder*i;
i *= 10;
}
sprintf(buff, "%d", binaryNumber );
return buff;
}
The fundamental problem is that you're trying to use an int to store your binary representation. An int is just that, an integer. In memory it's represented in binary, but the C syntax allows you to use base 10 and base 16 literals when assigning or doing other operations on ints. This might make it seem like it's not being treated as a binary number, but it really is. In your program you are confusing the base 2 representation and the base 10 representation. 891717742 (base 10) converted to binary is 110101001001101000100001101110. What your algorithm is essentially trying to do is store the base 10 number 110101001001101000100001101110 in an int. That base 10 number is larger than even a 64 bit number, it would actually would take 97 bits to store.
Check it this answer to see how you can print out the binary representation of an int in C: Is there a printf converter to print in binary format?
It is pretty much easy, can be done in two easy steps.
Int to hex string
int main()
{
int n=891717742;
char buff[100];
sprintf(buff, "%x", n);
printf("\n buff=%s", buff);
return 0;
}
Hex to binary
Please look at this
How to convert a hexadecimal string to a binary string in C

Convert int to binary string of certain size

I'm struggling to adapt to C after programming in Java for some time and I need help. What I'm looking for is a method that takes following input:
Integer n, the one to be converted to binary string (character array).
Integer length, which defines the length of the string (positions from the left not filled with the binary numbers are going to be set to default 0).
//Here's some quick code in Java to get a better understanding of what I'm looking for:
public static String convertToBinary(int length, int n) {
return String.format("%1$" + bit + "s", Integer.toBinaryString(value)).replace(' ', '0');
}
System.out.println(convertToBinary(8,1));
// OUTPUT:
00000001 (not just 1 or 01)
Any hints on what the equivalent of this would be in C? Also, could you provide me with an example of how the resulting binary string should be returned?
(not a duplicate, since what I'm looking for is '00000001', not simply '1')
The C standard library does not contain an equivalent function to Integer.toBinaryString(). The good news is, writing such a function won't be too complicated, and if you're in the process of learning C, this problem is fairly ideal for learning how to use the bitwise operators.
You'll want to consult an existing tutorial or manual for all the details, but here are a few examples of the sort of things that would be useful for this or similar tasks. All numbers are unsigned integers in these examples.
n >> m shifts all bits in n right by m steps, and fills in zeros on the left side. So if n = 13 (1101 in binary), n >> 1 would be 6 (i.e. 110), and n >> 2 would be 3 (i.e. 11).
n << m does the same thing, but shifting left. 3 << 2 == 12. This is equivalent to multiplying n by 2 to the power of m. (If it isn't obvious why that is, you'll want to think about how binary numbers are represented for awhile until you understand it clearly; it'll make things easier if you have an intuitive understanding of that property.)
n & m evaluates to a number such that each bit of the result is 1 if and only if it's 1 in both n and m. e.g. 12 & 5 == 4, (1100, 0101, and 0100 being the respective representations of 12, 5, and 4).
So putting those together, n & (1 << i) will be nonzero if and only if bit i is set: 1 obviously only has a single bit set, 1 << i moves it to the appropriate position, and n & (1 << i) checks if that position also has a 1 bit for n. (keeping in mind that the rightmost/least significant bit is bit 0, not bit 1.) So using that, it's a simple matter of checking each bit individually to see if it's 1 or 0, and you have your binary conversion function.
like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
char *convertToBinary(int length, int n) {
unsigned num = (unsigned)n;
int n_bit = CHAR_BIT * sizeof(num);
if(length > n_bit){
fprintf(stderr, "specified length greater than maximum length.\n");
length = n_bit;//or expand size?
}
char *bin = malloc(n_bit + 1);//static char bin[CHAR_BIT * sizeof(num)+1]; If you change, memmove(-->return p;), free is not necessary.
memset(bin, '0', n_bit);
bin[n_bit] = 0;
char *p = bin + n_bit;
do {
*--p = "01"[num & 1];
num >>= 1;
}while(num);
int bits = bin + n_bit - p;
if(bits < length){
p -= length - bits;
return memmove(bin, p, length + 1);
} else if(bits > length){
fprintf(stderr, "Specified length is not enough.(%s but length is %d)\n", p, length);
return memmove(bin, p, bits+1);//or cut off
/*
free(bin);
return ""; or return NULL;
*/
}// else if(bits == length)
return bin;
}
int main(void){
char *sbin = convertToBinary(8, 1);
puts(sbin);
free(sbin);
return 0;
}

How to convert binary int array to hex char array?

Say I have a 32 bit long array of 32 binary digits and I want to output that in Hex form. How would I do that? this is what I have right now but it is too long and I don't know how to compare the 4 binary digits to the corresponding hex number
This is what I have right now where I break up the 32 bit number into 4 bit binary and try to find the matching number in binaryDigits
char hexChars[16] ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char * binaryDigits[16] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
int binaryNum[32]= {'0','0','1','0','0','0','0','1','0','0','0','0','1','0','0','1','0','0','0','0','0','0','0','0','0','0','0','0','1','0','1','0'};
int currentBlock, hexDigit;
int a=0, b=1, i=0;
while (a<32)
{
for(a=i+3;a>=i;a--)
{
current=binaryNum[a];
temp=current*b;
currentBlock=currentBlock+temp;
b*=10;
}
i=a;
while(match==0)
{
if(currentBlock != binaryDigits[y])
y++;
else
{
match=1;
hexDigit=binaryDigits[y];
y=0;
printf("%d",hexDigit);
}
}
}
printf("\n%d",currentBlock);
I apologize if this isn't the crux of your issue, but you say
I have a 32 bit long array of 32 binary digits
However, int binaryNum[32] is a 32-integer long array (4 bytes per int, 8 bits per byte = 4 * 8 * 32 which is (1024 bits)). That is what is making things unclear.
Further, you are assigning the ASCII character values '0' (which is 0x30 hex or 48 decimal) and '1' (0x31, 49) to each location in binaryNum. You can do it, and do the gymnastics to compare each value to actually form a
32 bit long array of 32 binary digits
but if that is what you have, why not just write it that way? (as a binary constant). That will give you your 32-bit binary value. For example:
#include <stdio.h>
int main (void) {
unsigned binaryNum = 0b00100001000010010000000000001010;
printf ("\n binaryNum : 0x%8x (%u decimal)\n\n", binaryNum, binaryNum);
return 0;
}
Output
$ ./bin/binum32
binaryNum : 0x2109000a (554237962 decimal)
If this is not where your difficulty lies, please explain further, or again, just what you are trying to accomplish.

Check bit value at particular position in a binary with C language

I don't know why, I tried all the implementations I've found here in stack, but every of them have this strange behaviour.
My aim is: given a decimal, change it to binary and retrieve a bit at given position value.
Let's say I got this binary, which is decimal 255:
11111111
Well using this:
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))//other test
#define NCHECK_BIT(int, pos) (!! int & (1 << pos))
unsigned char* REG_SW ;
//from int to binary
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
int checkBitPosition(){
REG_SW = (unsigned char*) 0x300111;
return NCHECK_BIT(int_to_int(REG_SW [0]),6)==false?1:0 ;
}
it returns me true if the bit is 0 at sixth but also second (and some others..actually!!) so the results are impredictable... I didn't get the logic behind that gives me the result.
I assume that the int to binary translator works well, 'cause I'm printing that and it's always the correct binary taken from the int I give.
Can anybody help me?
Thanks in advance!
You are converting a number into its binary format first and then you are checking that binary format with your macros. This is wrong, since your macros will check for the position of the bit in the resulting number (not your original number) i.e,
first your number = 10 and binary format is 1010
now to check the bits you have to pass 10 as argument for your macros and not 1010
if you pass the binary representation 1010 to the macro then binary representation of the number 1010 will be checked for pos and not for 10.

How this code in C is working

I got a code in c which will do functionality of atoi function but i don't how its working
int main(int argc, char* argv[])
{
printf("\n%d\n", myatoi("1998"));
getch();
return(0);
}
int myatoi(const char *string)
{
int i;
i=0;
while(*string)
{
i=(i<<3) + (i<<1) + (*string - '0');
string++;
}
return(i);
}
In the above code is not getting incremented and always be zero then how (i<<3) + (i<<1) will effect the code?
(i<<3) + (i<<1) (for positive numbers at least) is equivalent to multiplying by 10, because i<<3 shifts the integer by 3 bits to the left (i.e. multiplying by 8) and i<<1 shifts the integer by 1 bit to the left (i.e. multiplying by 2).
Each time you encounter a new digit, it multiplies the current number by 10 and adds the new digit (i.e. if your current number is 199 and you encounter the digit 8, then your new number should be 1998 = 10 * 199 + 8.
The reason for subtracting '0' is that if your characters are encoded in ASCII, you need to convert the ASCII codes back to numbers.
For understanding this code, you need to understand:
(i<<3), I mean bit operators
and
*string, string++, I mean string manipulation and more generally operations on pointers.
You also need to know how strings are represented in C and how numbers are represented in ASCII.

Resources