Browse Source

refactoring: made code more readable and added comments

remotes/origin/conversionOfNumbers
Laurin 11 months ago
parent
commit
26343283e4
  1. 20
      src/conversionOfNumbers/conversionOfNumbers.c

20
src/conversionOfNumbers/conversionOfNumbers.c

@ -7,30 +7,38 @@
int binaryStrLen(int input){
int length = 0;
if (input == 0) return 1;
// Length for sign bit, working with negative numbers:
if (input < 0){
input *= -1;
length += 1;
}
// Calculate length needed for binary string:
for (int x = 0; x <= input; x++){
if(pow(2,x) >= input + 1){
length += x;
break;
}
}
return length;
}
char* convertIntToBinaryStr(int input){
int length = binaryStrLen(input);
int rest;
char* result = (char*)malloc(sizeof(char) * length + 1);
if(result == NULL) return NULL;
// Add sign bit:
if(input < 0){
result[0] = '-';
input *= -1;
}
// Terminate string:
result[length] = '\0';
// Algorithm to build binary string:
do{
rest = input % 2;
input /= 2;
@ -38,6 +46,7 @@ char* convertIntToBinaryStr(int input){
if(rest == 0) result[length - 1] = '0';
length--;
}while(input != 0);
return result;
}
@ -45,32 +54,40 @@ unsigned int convertBinaryStrToInt(char* input){
unsigned int result = 0;
int index = strlen(input) - 1;
int exponent = 0;
// Algorithm to calculate number for given binary string:
while(index >= 0){
if(input[index] == '1') result += 1 * pow(2, exponent);
index--;
exponent++;
}
return result;
}
int hexStrLen(const int input){
int length = 0;
if(input == 0) return 1;
// Calculate length needed for hexadecimal string:
for (int x = 0; x <= input; x++){
if(pow(16,x) >= input + 1){
length += x;
break;
}
}
return length;
}
char* convertIntToHex(int input){
int length = hexStrLen(input);
int rest;
char* result = (char*)malloc(sizeof(char) * length + 1);
if(result == NULL) return NULL;
// Terminate string:
result[length] = '\0';
// Algorithm to build hexadecimal string:
do{
rest = input % 16;
input /= 16;
@ -85,6 +102,7 @@ char* convertIntToHex(int input){
}
length--;
}while(input != 0);
return result;
}
@ -92,6 +110,7 @@ unsigned int convertHexStrToInt(char* input){
unsigned int result = 0;
int index = strlen(input) - 1;
int exponent = 0;
// Algorithm to calculate number for given hexadecimal string:
while(index >= 0){
switch(input[index]){
case 'A': case 'a': result += 10 * pow(16, exponent); break;
@ -105,5 +124,6 @@ unsigned int convertHexStrToInt(char* input){
index--;
exponent++;
}
return result;
}
Loading…
Cancel
Save