Menu

Typecasting

2002-09-10
2012-09-26
  • Nobody/Anonymous

    Hi
    I'm very much a beginner so go easy on me if this is a dumb question :)

    I understand how a character can be made to appear as an integer the integer being it's ascii code value using type casting.

    What I am doing at the moment is writing some code which deals with Hex numbers which are stored as character strings.  eg F889CA2B

    I need to turn these into hex values for each byte so I can perform some logical operation on those values.

    I can figure how to write a function that do this....
    look at each characterin turn
    convert it to an integer from 0 to 15
    multiply the high nibble value by 16
    add low nibble value.

    but am i reinventing the wheel here? is there some built in functions to deal with hex values to save me the bother??

    also how do i refer to an integer as an hex value rather than a decimal one?  do I use $81 or 0x81 or some such?

    dicky

     
    • Nobody/Anonymous

      No helpers????

       
    • Nobody/Anonymous

      don't no if there is a "standard" solution, but reinventing the wheel is not necessary if can copy past it from the net. I think this:
      http://www.codeproject.com/string/hexstrtoint.asp
      is what you are looking for.
      You may need to modify it a little because it uses the 0xABCD input convention (your second question) and also it is written for vc++ (so remove the first include and maybe the tchar stuff...)

      stephan

       
    • Nobody/Anonymous

      #include <iostream>
      #include <iomanip>
      using namespace std;

      int main () {
        int i;
        cin  >> setbase(16) >> i;
        cout << i << endl;
        return 0;
      }

      This trick also works, run it and type a hex number and it will convert it to dec. Just look into iostream and iomanip. You can find some info here:
      http://www.cplusplus.com/ref/indexr.html

      stephan

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.