Conversion hexadecimal to decimal - c

I've already written a program, but it's a bit incorrect.
I will be very grateful if you show me how to fix it.
So, here is the trouble:
You have to convert the number from hexadecimal to decimal form.
The main problem is that program must CALCULATE MANUALLY the number , instead of using a format specification ( as i did )
I apologize for possible inaccuracies and mistakes in English, I am just starting to familiarize myself with programming))
There is my variant:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define SIZE 20
int main(void) {
system("chcp 1251");
char str[SIZE][SIZE], (*pstr)[SIZE];
pstr = str;
char* pcode;
int kst;
printf("Specify the number of lines you want to enter: ");
scanf_s("%d", &kst);
getchar();
while (kst > SIZE)
{
printf("You have exceeded the allowed value (the number of lines must be less than 20): ");
scanf_s("%d", &kst);
getchar();
}
while (kst < 1)
{
printf("You entered a number that is too small, try entering a number between 1 and 20:");
scanf_s("%d", &kst);
getchar();
}
int isXDigit;
printf("\nEnter the lines:\n\n");
while (pstr < str + kst)
{
isXDigit = 1;
gets_s(*pstr);
for (pcode = *pstr; *pcode != '\0'; pcode++){
if (isxdigit(*pcode) == 0){
**pstr = 0;
break;
}
}
pstr++;
}
printf("\nThe result\n");
unsigned long long sixteen;
for (pstr = str; pstr < str + kst; pstr++)
{
if (**pstr == 0)
printf("16: The error!\n");
else {
sixteen = strtoull (*pstr, NULL, 16);
printf("16: %#020llx | 10: %llu\n", sixteen, sixteen);
}
}
return 0;
}

unsigned long long hexToNum(const char *hexSTR)
{
const char *digits = "0123456789ABCDEF";
const char *found = NULL;
unsigned long long result = 0;
while(*hexSTR)
{
result *= 0x10;
if(found = strchr(digits, toupper((unsigned char)*hexSTR)))
result += found - digits;
else { result = 0; break;}
hexSTR++;
}
return result;
}

Textual representation of a number
“Hexadecimal” and “decimal” (and “octal” and “binary” et cetera) are all textual representations of a number.
That is, we write numbers with a radix, but a number exists independently of any particular representation.
That is why 0xA equals 10 equals 012 equals 0b1010 (hexadecimal, decimal, octal, and binary representations).
Remember in grade school when you were taught digit places? That is because a number is a polynomial representation of a value.
→ 123 equals 100 + 20 + 3
Or, written as a polynomial:
 → 1×102 + 2×101 + 3×100
That 10 is the radix. If we change the radix, the number gets written differently. The following, even though it has the same digits, is a totally different number:
 → 1×162 + 2×161 + 3×160
We can see this by doing the math.
3×160 is 3
2×161 is 32
1×162 is 256
256 + 32 + 3 is 291
Dissecting a number to a polynomial representation with radix
To get the least-significant digit of a number, you simply take the remainder of dividing it by the radix:
 → 123 ÷ 10 is 12 with a remainder of 3
You can repeat this process to get every digit in the given radix:
 → 12 ÷ 10 is 1 with a remainder of 2
 → 1  ÷ 10 is 0 with a remainder of 1
So the digits, radix 10, of 123 are, least-significant to most-significant, 3, 2, and 1. We write this as 123.
Suppose we take a radix of 16?
 → 123 ÷ 16 is 7 with a remainder of 11 (which we write as B)
 → 7   ÷ 16 is 0 with a remainder of 7
So the hexadecimal (radix == 16) value of 123 is 7B.
Suppose we take a radix of 8?
 → 123 ÷ 8 is 15 with remainder 3
 → 15  ÷ 8 is 1 with remainder 7
 → 1   ÷ 8 is 0 with remainder 1
So the octal (radix == 8) value of 123 is 173.
In C the operators for getting the quotient and remainder are / and %:
42 / 10 is 4 (quotient)
42 % 10 is 2 (remainder)
Building a number from a polynomial representation with radix
If you are given a textual number representation and wish to build that into an actual numeric value, you only need to know the radix and have access to multiplication and addition.
For example, given 2 7 B:
0 * 16 + 2 → 0 + 2 → 2
2 * 16 + 7 → 32 + 7 → 39
39 * 16 + 11 → 624 + 11 → 635
Indeed this is correct: The hexadecimal representation of 635 is 27B. Said another way, the decimal representation of 0x27B is 635.
Functions!
We can make ourselves functions both to build and dissect polynomial text representations.
int hex_to_int( const char * text );
void int_to_hex( int number, char result[] );
Digit symbols
One thing to be aware of is the number of digit symbols available to a given radix.
For decimal we use the digit symbols 0 through 9.
For octal we only use the digit symbols 0 through 7.
For binary we only need 0 and 1.
But we don’t have enough Arabic digit symbols for hexadecimal, which needs 16 digit symbols. So we just start using the alphabet:
 → 0 1 2 3 4 5 6 7 8 9 A B C D E F
Converting to hex is easy. Just use an array:
char digits[] = "0123456789ABCDEF";
To output the digit symbol for digit 13, just use the array:
printf( "%c", digits[13] ); // prints "D"
Going the other way is a little trickier. I recommend you make yourself a little function:
int hex_digit_to_value( int digit )
{
if ((digit >= '0') and (digit <= '9')) return (digit - '0');
if ((digit >= 'A') and (digit <= 'F')) return (digit - 'A') + 10;
if ((digit >= 'a') and (digit <= 'f')) return (digit - 'a') + 10;
return 0; // can't happen? maybe return -1?
}

Related

Why I should subtract '0' so that I can do int_arr[5] = char_string[5]?

So I was assigned to store two 50 digit integers in c language and do math equations using them. the problem for me was to store the input digit by digit in an array. I figured that I can store the input in a char string like this:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char string_test [50];
scanf("%s", string_test);
return 0;
}
But I couldn't use it as a number because it was stored as char and I couldn't copy them digit by digit into another array which was defined as int
after a whole day of searching, I found out that I need to copy my string one by one like this:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char string_test [50];
scanf("%s", string_test);
int arr[50];
for (int i = 0; i < 50; i++)
{
arr[i] = string_test[i] - '0';
}
return 0;
}
Now my question is why do I need to subtract '0' to get a suitable result?
The ASCII values for digits 0 - 9 are:
Digit 0 1 2 3 4 5 6 7 8 9
ASCII value 48 49 50 51 52 53 54 55 56 57
So if you have a string representation of an integer, say
char int_str[] = "123456";
and need to convert each char to its numeric value, subtracting the value for '0' (48) from each will will result in the values
int_str[0] == '1' ==> '1' - '0' ==> 42 - 41 == 1
int_str[1] == '2' ==> '2' - '0' ==> 43 - 41 == 2
int_str[2] == '3' ==> '3' - '0' ==> 44 - 41 == 3
int_str[3] == '4' ==> '4' - '0' ==> 45 - 41 == 4
int_str[4] == '5' ==> '5' - '0' ==> 46 - 41 == 5
int_str[5] == '6' ==> '6' - '0' ==> 47 - 41 == 6
To get digits 1 2 3 4 5 6 into the integer 123456 requires additional steps:
This example uses the same conversions encapsulated into a function to convert discrete char digit to int digit values, then assimilate each discrete int digit value into the composite integer value:
int main(void)
{
char str[] = "123456";
int int_num = str2int(str);
return 0;
}
int str2int(char *str)
{
int sum=0;
while(*str != '\0')
{ //qualify string
if(*str < '0' || *str > '9')
{
printf("Unable to convert it into integer.\n");
return 0;
}
else
{ //assimilate digits into integer
sum = sum*10 + (*str - '0');
str++;
}
}
return sum;
}
A char like '0' is just an ASCII representation of a 1 byte number. The numeric representations of these characters can be found in the manual (man ascii). Here you will see that '0' actually represents number 48 or 0x30 and that ASCII '0' to '9' are consecutive.
To convert a numeric char value to its integer counterpart, it is necessary to subtract this value of 48 or '0'.
I hope this clears things up. For further info, look into char arithmetic in C.
This is actually related to the ASCII code representation of numbers; when you input a character, '0', it is stored in memory as value 48 (in decimal) and also any other number or character.
You will find that the ASCII code value for '1' is 49 so, if we applied the operation, int x = '1' - '0';, we are storing the decimal value 1 in x and dealing with it as a number, not a character any more.
You can search more about ASCII codes; it's a very useful topic for any programmer.

How to store multiple value of printf in a variable?

The program must accept an integer N with even number of digits as the input.
The program must reverse every two digits in N and print the modified N as the output.
Boundary Condition(s): 10 <= N < 10^16
Input Format: The first line contains N.
Output Format: The first line contains the modified N.
Example Input/Output 1:
Input: 214587
Output: 125478
Explanation: The first two digits are 2 and 1 which are reversed as 1 and 2. The second two digits are 4 and 5 which are reversed as 5 and 4. The third two digits are 8 and 7 which are reversed as 7 and 8.
Example Input/Output 2:
Input: 504786
Output: 57468
I have proceeded in a logic of printing the values inside a while loop by printing b/10 and b%10; where the output should be reversed and I am stuck in it, please help in my logic how to proceed further thank you.
scanf("%d",&a);
while(a>0) {
b=a%100;
printf("%d%d",b/10,b%10);
a=a/100;
}
As I noted in three comments (1, 2, 3), I think you need to use recursion, and some care. Here is code that works, and a test harness (which is bigger than the code being tested) demonstrating that it works:
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static bool reverse_digit_pairs(uint64_t value)
{
uint64_t b = value % 100;
uint64_t v = value / 100;
if ((v > 0 && v < 10) || (v == 0 && b < 10))
return false;
int t = b / 10; // tens
int u = b % 10; // units
bool ok = true;
if (v >= 10)
ok = reverse_digit_pairs(v);
if (ok)
{
if (u == 0 && v == 0)
printf("%d", t);
else
printf("%d%d", u, t);
}
return ok;
}
static void test_reverse_digit_pairs(uint64_t v)
{
printf("V: %20" PRIu64 " = ", v);
if (!reverse_digit_pairs(v))
{
fprintf(stderr, "Odd number of digits in %" PRIu64 "\n", v);
printf("bogus input");
}
putchar('\n');
fflush(0); // Ensure standard output (and standard error) are flushed.
}
int main(void)
{
test_reverse_digit_pairs(UINT64_C(214587)); // 125478 per question
test_reverse_digit_pairs(UINT64_C(504786)); // 57468 per question
test_reverse_digit_pairs(UINT64_C(5047000086)); // Pairs of zeros
test_reverse_digit_pairs(UINT64_C(5047900086)); // Pair of zeros
test_reverse_digit_pairs(UINT64_C(1234567890123456)); // 16 digits
test_reverse_digit_pairs(UINT64_MAX); // 20 digits
test_reverse_digit_pairs(UINT64_C(123456789012345)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(0)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(1)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(9)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(10)); // 2 digits
test_reverse_digit_pairs(UINT64_C(99)); // 2 digits
test_reverse_digit_pairs(UINT64_C(100)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(999)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(1000)); // 4 digits
test_reverse_digit_pairs(UINT64_C(1098)); // 4 digits
test_reverse_digit_pairs(UINT64_C(1234)); // 4 digits
return 0;
}
The output I get from it is:
V: 214587 = 125478
V: 504786 = 57468
V: 5047000086 = 574000068
V: 5047900086 = 574090068
V: 1234567890123456 = 2143658709214365
V: 18446744073709551615 = 81447644707390556151
Odd number of digits in 123456789012345
V: 123456789012345 = bogus input
Odd number of digits in 0
V: 0 = bogus input
Odd number of digits in 1
V: 1 = bogus input
Odd number of digits in 9
V: 9 = bogus input
V: 10 = 1
V: 99 = 99
Odd number of digits in 100
V: 100 = bogus input
Odd number of digits in 999
V: 999 = bogus input
V: 1000 = 100
V: 1098 = 189
V: 1234 = 2143
The test cases for the numbers with 1 to 4 digits were necessary to flush out some issues. I'm not completely happy with the first condition in reverse_digit_pairs(), but I didn't get the output I think is required when I tried some simplifications.

How to get every digit from a number in C?

I have these variables:
int dividend;
 int divider;
And I have the function :
Divisibility7 (int num);
Those two variables will be at the main function, and the user will be asked to enter the dividend and divider, but in case the user enter the divider 7, then, the function above will be called.
The problem is that I have to follow specific criteria to do this. So let's say the user will enter with the dividend 7203. This happen :
I. Get the last digit of the number.
Last digit: 3
Ii. Multiply the last digit by 2
3 x 2 = 6
Iii. Get the value of the initial number, without the last digit.
720
Iv. Subtract the initial value without the last digit from the multiplication result.
fabs (720 - 6) = 714
V. Repeat the process until the result is a value less than or equal to 70
Vi. Compare the result with the table of contents (0, 7, 14, 21, 28, 35, 42, 49, 54, 63, 70) for
Determine whether or not the number is divisible by 7
Code :
int res;
int x;
int y;
int Divisibility7(int num) {
int res;
int x;
int y;
int z;
while(num > 70) {
x = num % 10; // get the last digit from the number
y = x * 2; // multiply the last digit by 2;
z = num/10; // get the first digits from the number
fabs(z - y); // subtract the first digits with the last digits;
}
}
In the part of the while, the final fabs(z-y) returns what I want, to be the first digits subtracting the last number, but the problem is that the while stop there, I have to do something to make this while go till 70 or less.
PS : I need to check if the final number from the iterations, it's a number multiplied by 7, how can I do that ? And I can't use mod for this.
You have not changed num in your while loop . Also you do no return the value . Hope the following code will be ok for you .
int Divisibility7(int num) {
int res,x,y,z;
while(num > 70) {
x = num % 10; // get the last digit from the number
y = x * 2; // multiply the last digit by 2;
z = num/10; // get the first digits from the number
num = abs(z - y); // subtract the first digits with the last digits;
}
if(num == 0 || num == 7 || num == 14 || num == 21 || num == 28 || num == 35 || num == 42 || num == 49 || num == 54 || num == 63 || num == 70) {
return 1;
}
else {
return 0;
}
}
Not sure, but I think this is what are you trying to do:
int main (void)
{
int number, lastDigitMultiplied;
scanf("%d", &number);
while(number > 70){
//get the last digit and multiply it by 2
lastDigitMultiplied = (number % 10) * 2;
//subtract the initial value without the last digit from the multiplication result.
number = number / 10 - lastDigitMultiplied;
}
if(abs(number) % 7 == 0)
printf("The result is %d and it is a multiple of 7", number);
else
printf("The result is %d and it is not a multiple of 7", number);
return 0;
}
for divisibility against 7, if you have a positive large bigint already formatted as a string, don't waste time with the regular method doing it 1 digit at a time.
powers of 10, mod 7, repeats every 6 rounds :
10^1 % 7 = 3 10^7 % 7 = 3 10^13 % 7 = 3
10^2 % 7 = 2 10^8 % 7 = 2 10^14 % 7 = 2
10^3 % 7 = 6 10^9 % 7 = 6 10^15 % 7 = 6
10^4 % 7 = 4 10^10 % 7 = 4 10^16 % 7 = 4
10^5 % 7 = 5 10^11 % 7 = 5 10^17 % 7 = 5
10^6 % 7 = 1 10^12 % 7 = 1 10^18 % 7 = 1
meaning, the effects of the digits mod 7 stay identical as long as they're in chunks of 6 digits at a time.
the largest multiple of 6-digits supported by double precision FP to full integer precision would be 12-digits at a time.
So the way to do it is to right-align the digits by padding leading edge zeros to ensure string length is a multiple of 12. Then simply add the digits onto each other, performing a single mod % 7 operation once every 9000 or so rounds of the addition loop
—- (that's when you run up against 2^53 limit; 9007 rounds if u wanna be pedantic about it)
example :
x = 71400535477047763120175175402859619447790
02233464423375355339031113233806609150957
x % 7 = 4
now try summing up chunks of 12 :
007140053547704776312017517540285961944779
002233464423375355339031113233806609150957
007140053547 7140053547
704776312017 711916365564
517540285961 1229456651525
944779002233 2174235653758
464423375355 2638659029113
339031113233 2977690142346
806609150957 3784299293303
----------------------------
3784299293303 % 7 = 4
it works exactly the same for any multiples of 6 : e.g. 6, 18, 24, and 30 --
00714005354770477631201751754
02859619447790022334644233753
55339031113233806609150957
312017 312017
517540 829557
285961 1115518
944779 2060297
002233 2062530
464423 2526953
375355 2902308
339031 3241339
113233 3354572
806609 4161181
150957 4312138
007140 4319278
053547 4372825
704776 5077601
----- -------
_ 5077601 % 7 = 4
00000000714005354770477631201
75175402859619447790022334644
23375355339031113233806609150957
464423375355339031 464423375355339031
113233806609150957 577657181964489988
000000007140053547 577657189104543535
704776312017517540 1282433501122061075
285961944779002233 1568395445901063308
---------------------------------------
1568395445901063308 % 7 = 4
00000000000000714005354770477
63120175175402859619447790022
33464423375355339031113233806
609150957
339031113233806609150957 339031113233806609150957
000000000000007140053547 339031113233813749204504
704776312017517540285961 1043807425251331289490465
944779002233464423375355 1988586427484795712865820
---------------------------------------------------
1988586427484795712865820 % 7 = 4
000000007140053547704776312017517
540285961944779002233464423375355
339031113233806609150957
000000007140053547704776312017 7140053547704776312017
517540285961944779002233464423 517540293101998326707009776440
375355339031113233806609150957 892895632133111560513618927397
892895632133111560513618927397 % 7 = 4

Binary to decimal algorithm in c giving strange results

Hi i'm fairly new to c but for a program I'm writing I need to convert binary strings to decimal numbers. here is my current code:
int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++)
{
if(binaryString[i] == '1')
decimal += 2^((len - 1) - i);
printf("i is %i and dec is %i and the char is %c but the length is %i\n", i, decimal, binaryString[i], len);
}
return decimal;
}
int main(int argc, char **argv)
{
printf("%i", BinaryToInt("10000000"));
}
and here is the output:
i is 0 and dec is 5 and the char is 1 but the length is 8
i is 1 and dec is 5 and the char is 0 but the length is 8
i is 2 and dec is 5 and the char is 0 but the length is 8
i is 3 and dec is 5 and the char is 0 but the length is 8
i is 4 and dec is 5 and the char is 0 but the length is 8
i is 5 and dec is 5 and the char is 0 but the length is 8
i is 6 and dec is 5 and the char is 0 but the length is 8
i is 7 and dec is 5 and the char is 0 but the length is 8
5
I'm confused as to why this doesn't work, all help is greatly appreciated. Thanks in advance!
Ps: I'm used to java so at the moment C just makes me cry
The ^ operator is not for exponentiation, but is instead the bitwise XOR operator.
If you want to raise a number to a power of 2, use the left shift operator << to shift the value 1 by the exponent in question.
decimal += 1 << ((len - 1) - i);
The trick is the same as with any number base: for each incoming digit, multiply the accumulator by the number base and add the digit.
#include <stdio.h>
#include <string.h>
int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++) {
decimal = decimal * 2 + binaryString[i] - '0';
}
return decimal;
}
int main(void)
{
printf("%d", BinaryToInt("10000000"));
return 0;
}
Program output:
128

Count total number of digits from a given positive number without looping in C

How to count total number of digits from a given positive number without looping in C?
For integers, take the log10 of the number, round down, and add one.
TEST:
#include <math.h>
#include <stdio.h>
int
num_digits(unsigned long number)
{
return (int)(floor(log10((double)number)) + 1.0);
}
int
main(int argc, char **argv)
{
unsigned long test_numbers[] = {
1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 99999, 100000, 999999,
123456789ul,
999999999ul,
0
};
unsigned long *ptr;
for(ptr = test_numbers; *ptr; ptr++)
{
printf("Number of digits in %lu: %d\n", *ptr, num_digits(*ptr));
}
return 0;
}
Output:
Number of digits in 1: 1
Number of digits in 9: 1
Number of digits in 10: 2
Number of digits in 99: 2
Number of digits in 100: 3
Number of digits in 999: 3
Number of digits in 1000: 4
Number of digits in 9999: 4
Number of digits in 10000: 5
Number of digits in 99999: 5
Number of digits in 100000: 6
Number of digits in 999999: 6
Number of digits in 123456789: 9
Number of digits in 999999999: 9
One possible solutions, assuming 16-bit integer values and logical expressions evaluating to 0 or 1. You could replace the conditions with (u > 99) ? 1 : 0 if you're worried about portability.
int digits( unsigned u)
{
return 1 + (u > 9) + (u > 99) + (u > 999) + (u > 9999);
}
Two solutions for you!
int digit_count(unsigned int n)
{
if (n < 10)
return 1;
else
return (1 + digit_count(n / 10));
}
and
unsigned int n = 50;
int i = 0;
HACK:
i++;
if (n < 10)
{
printf("Digits: %d\n", i);
}
else
{
n /= 10;
goto HACK;
}
Don't hate me for the last one :(
return snprintf(0, 0, "%d", num);

Resources