pad.mattdiesel.co.uk

Snippet - String To Hex

String To Hex (C++)

Convert a string to hex
Created 2014-05-09 14:17:28.025970 by Matt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>


int main( int argc, char const* argv[] )
{
    for ( char const** arg = &argv[1]; --argc; arg++ ) {
        for ( char const* c = *arg; *c; c++ ) {
            if ( ( *c >> 4 ) < 10 ) {
                std::cout << ( char )( '0' + ( *c >> 4 ) );
            }
            else {
                std::cout << ( char )( 'A' + ( *c >> 4 ) - 10 );
            }

            if ( ( *c & 0xF ) < 10 ) {
                std::cout << ( char )( '0' + ( *c & 0xF ) );
            }
            else {
                std::cout << ( char )( 'A' + ( *c & 0xF ) - 10 );
            }
        }

        if ( !( argc - 1 ) ) {
            break;
        }

        std::cout << "20";
    }

    std::cout << std::endl;

    return 0;
}