CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Hex converting

  1. #1
    Join Date
    May 2002
    Location
    Germany
    Posts
    451

    Hex converting

    Hello,

    What is the fastest way to convert a string represents four hex values as a continuous flow (for example char*c = "10FF36CC") to convert to a string contains decimal values [and perhaps separator dots]? 16.255.54.204
    ?

  2. #2
    Join Date
    Aug 2002
    Location
    VA, USA
    Posts
    137
    luftwaffe,

    The example I'm providing uses STL strings and streams to get
    the job done. The code assumes the input string is comprised
    of consecutive hex numbers that are two characters long. I
    threw it together quickly as a starting place for you. You can
    probably optimize it if you do some profiling.

    Code:
    bool make_decimal_ip_str(const std::string& in_str, std::string& out_str)
    {
        out_str.erase();
        std::string::size_type pos = 0;
        
        while (pos < in_str.size()) {
    	// Isolate two char hex 
    	std::string hex_str = in_str.substr(pos, 2);
    
    	// Extract integer val from hex string
    	std::istringstream iss(hex_str);
    	int val = 0;
    	iss >> std::hex >> val;
    	if (iss.fail())
    	    return false;
    
    	// Insert integer value to string as decimal
    	std::ostringstream oss;
    	oss << val;
    	if (oss.fail())
    	    return false;
    
    	// Build result string
    	out_str += oss.str() + ".";
    
    	// Increment substring pos
    	pos += 2;
        }
    
        // Remove last dot
        out_str.erase(out_str.end()-1);
        return true;
    }
    
    int main(int argc, char* argv[])
    {
        std::string result_str;
        std::string input_str = "10FF36CC";
    
        make_decimal_ip_str(input_str, result_str);
    
        std::cout << "hex: " << input_str << "  dec: " << result_str << std::endl;
        return 0;
    }
    regards, willchop

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