How To Remove Characters?
I'm start(really starting) an Assembly tool, at the time it only converts a decimal to a hexadecimal, but I want to remove the zeros from the result. Here is the code:
// HexConvert.cpp
#include <iostream>
using namespace std;
int main()
{
    int decNumber;
    while (true)
    {
       cout << "Enter the decimal number: ";
       cin >> decNumber;
       // Print hexadecimal with leading zeros
       cout << "Hexadecimal: ";
       for (int i = 2*sizeof(int) - 1; i >= 0; i--)
       {
          cout << "0123456789A开发者_如何学PythonBCDEF"[((decNumber >> i*4) & 0xF)];
       }
       cout << endl;
    }
  return 0;
}
How can I do this?
Your for loop should have two states:
- Starting state which ignores '0' characters, but switches to the next state on non-'0'
- Print every character to the end.
So, the first state will need to check each character before printing.
How about:
int number = 56;
cout << hex << number;
You could also pass through stringstream to get the hex string representation, with:
#include <iostream>
#include <sstream>
int main () {
    int number = 45;
    std::ostringstream os;
    os << std::hex << number;
    std::cout << os.str() << std::endl;
}
And more info on stringstreams and fromString/toString: http://cplusplus.co.il/2009/08/16/implementing-tostring-and-fromstring-using-stdstringstream/
You can call this function directly from C++, but you may have to save some registers, dependig on the compiler. Have fun retranslating to C++.
        ;number to convert in [esp+4]
        ;pointer to string in [esp+8]
itoh:   mov edi, [esp+8]   ;pointer to c string
        bsr ecx, eax       ;calculate highest set bit
        and cl, $fc        ;round down to nearest multiple of 4
loop:   mov eax, [esp+4]
        shr eax, cl        ;mov hex digit to lowest 4 bit
        and eax, $f        ;mask hex digit
        cmp eax, 10        ;test if digit is in A..F
        jlt numdgt
        add eax, 'A'-'0'-10 ;it is
numdgt: add eax, '0'       ;ascii converted digit
        mov [edi], al      ;store to string
        inc edi            ;and increment pointer
        sub cl,4           ;decrement loop counter
        jnc loop
        mov byte[edi], 0   ;terminate string
        ret
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论