Click to See Complete Forum and Search --> : Hexadecimal Functions


barbes
September 30th, 2002, 09:48 PM
Hi,
Does anyone know of any hexadecimal built in functions that could be used to add - subtract - multiply - two hexadecimal numbers together. Just wondering if there was any prewritten functions out there??

CBasicNet
October 1st, 2002, 12:39 AM
What do you mean? Decimal, hexidecimal and binary are just different representations of the same number. You can use the same mathematical operations on them.

int a=0x10; //=16 in base 10
int c, b=0x04; //=4 in base 10

c=a+b;
printf("%x", c); //prints 0x14
printf("%d", c); //prints 20

They are the same thing.

If you are talking about hex strings like "0x10" and "0x04", yes, you need to convert them from strings to integers before adding.

barbes
October 1st, 2002, 12:59 AM
What I mean is....
User enters in Hex number 1 ie. 10A
User enters in Hex number 2 ie. FC
Program then calculates the answer in HEX value...ie 10A + FC = 206 in Hexadecimal. What I need is a function that converts both Hex numbers into decimal equivalent, once these numbers are in decimal the program can then do the necessary operations. ie. Add the two numbers, multiply, or subtract, depending on what menu option the user selects. After the decimal value is calculated, it is then transformed back to the Hex equivalent answer. The calculated Hex value is then returned to the user...

owenrb
October 1st, 2002, 01:04 AM
Additional Info:

You can use sscanf( ) function to convert hex strings into integer value.
For example:


char strnum[] = "0xFE";
int num;

sscanf(strnum, "%x", &num);

CBasicNet
October 1st, 2002, 01:35 AM
Read in the input as string.

Then use sscanf() in <stdio.h> as owen says to convert it to integer.

Do whatever operations you want with the integer.

Then use itoa() in <stdlib.h> to convert it to a hex string. Remember to set the radix parameter to 16

Then display the string.