CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 1999
    Location
    Cincinnati, Ohio
    Posts
    195

    Alphanumeric division (base 10 to base 16)

    Folks,

    Alphanumeric division

    Folks,

    I have a dilemma. I have an alphanumeric number that is 24 digits long, which is base ten. I need to convert it to base 16. I know that I can divide the whole number by 16 to get the first digit, and then divided the answer again to get the next digit.

    Example:

    Start with 513 (we all know that 201h)

    513/16 = 32 R1
    32/16 = 2 R0
    2/16 = 0 R2

    Unroll it and you have the 201. Now I know that it is possible to do long division on a alphanumeric number, but I was wondering if there way any preexisting code samples to do alphanumeric division. Or is there a better way to achieve what I am trying to do?

    Sam

  2. #2
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    2,236
    std::ostringstream ss;
    long n = 513;
    ss << hex << n;
    ss.str(); // = hex version of n ( 0x0201 )

    If you have some desire to convert it yourself you should know that the digits of hex are:

    1 | 16 | 256 | 4096 ...

    So. To get the 4096 in this case, we should int divide by 4096 and process the remainder:

    513 / 4096 = 0
    513 % 4096 = 513.

    Then we go on to 256:

    513 / 256 = 2
    513 % 256 = 1

    Then 16:

    1 / 16 = 0
    1 % 16 = 1

    Then 1:

    1 / 1 = 1
    1 % 1 = 0 // should end up with 0 if your algrithm works

    So basically you use need a reverse loop starting at how over many digits will be in your hex string ( exp( 16, strlen-1 ) ).
    Last edited by mwilliamson; March 7th, 2003 at 06:56 PM.

  3. #3
    Join Date
    Dec 1999
    Location
    Cincinnati, Ohio
    Posts
    195
    a couple problems here. First of the number that I have is this:

    char number[25];
    strcpy(number, "123546789123456789123456");

    This I need to get to hex:

    7C1FB0D758001180h

    I used the calculator that come with windows to do the conversion, but I don't think that will work programmtically

    [ccode]std::stringstream[/ccode] will not work because the number is a string. (I believe that I was mistaken in saying alphanumeric.)

    And finally:

    F1h (0xF1) is 241 base 10.
    FFh is 255, so --> 100h is 256.
    100h + 100h = 200h, and 256 + 256 = 512, so --> 200h = 512.
    200h + 1h = 201h, 512 + 1 = 513, so --> 201h = 513

    If you still doubt me, play with the Windows calculator in Scientific mode.

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