CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Aug 2002
    Posts
    16

    Hexadecimal Functions

    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??

  2. #2
    Join Date
    Sep 2002
    Location
    Singapore
    Posts
    673
    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.

    Code:
    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.

  3. #3
    Join Date
    Aug 2002
    Posts
    16
    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...

  4. #4
    Join Date
    Sep 2002
    Location
    Philippines
    Posts
    197
    Additional Info:

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

    Code:
    char strnum[] = "0xFE";
    int  num;
    
    sscanf(strnum, "%x", &num);

  5. #5
    Join Date
    Sep 2002
    Location
    Singapore
    Posts
    673
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured