Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define LEN 10
- char* intBinToString(int x);
- int stringBinToInt(char* s);
- int lengthBin(int x);
- char* intBinToString1(int x);
- int stringBinToInt1(char* s);
- int main()
- {
- int broj, x;
- char *s=NULL;
- printf("Broj: ");
- scanf("%d",&broj);
- s = intBinToString(broj);
- printf("Binarni zapis broja: %s",s);
- x = stringBinToInt(s);
- printf("\nx = %d",x);
- s = intBinToString1(broj);
- printf("\n\nBinarni zapis broja: %s",s);
- x = stringBinToInt1(s);
- printf("\n\nx = %d",x);
- return 0;
- }
- char* intBinToString(int x)
- {
- char* s = (char* )malloc(LEN * sizeof(char));
- char *poc = s, *kraj=s, temp;
- while(x){
- if(x%2) *kraj='1';
- else *kraj='0';
- kraj++;
- x/=2;
- }
- *kraj=NULL;
- kraj--;
- while(kraj>poc){
- temp=*kraj;
- *kraj=*poc;
- *poc=temp;
- kraj--;
- poc++;
- }
- return s;
- }
- int stringBinToInt(char* s)
- {
- int broj=0;
- while(*s){
- broj=2*broj+(*s-'0');
- s++;
- }
- return broj;
- }
- int lengthBin(int x)
- {
- int br=0;
- while(x){
- br++;
- x>>=1;
- }
- return br;
- }
- char* intBinToString1(int x)
- {
- char* s = (char* )malloc(LEN * sizeof(char));
- char* poc = s;
- int len = lengthBin(x), i;
- for(i=len;i>=0;i--){
- *poc = ((x & (1<<i))>>i)+'0';
- poc++;
- }
- *poc=NULL;
- return s;
- }
- int stringBinToInt1(char* s)
- {
- int x=0;
- while(*s){
- x<<=1;
- x|=(*s-'0');
- s++;
- }
- return x;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement