Category ArchiveCode



C++ 31 Jan 2010 11:31 pm

Snippet: Convert String to Hex

//tinodidriksen.com/uploads/code/cpp/string-to-hex.cpp

#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>

int main() {
    std::string str("abcABC123\xff\x01");
    std::stringstream ss;
    for (size_t i=0 ; i<str.length() ; ++i) {
        ss << std::setw(2) << std::setfill('0')
            << std::hex << (int(str[i])&0xFF);
    }
    std::cout << ss.str();
}

C 31 Jan 2010 11:29 pm

Snippet: Convert Hex to Text

//tinodidriksen.com/uploads/code/c/hex-to-text.c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    char buf[] = "54657374";
    size_t len = strlen(buf);

    if (len & 1) {
        printf("Cannot take hex from odd length string.\n");
        exit(1);
    }

    char *result = (char*)malloc(len/2 + 1);
    memset(result, 0, len/2 + 1);
    for (size_t i = 0 ; i < len/2 ; ++i) {
        char tmp[3] = {buf[i*2], buf[i*2+1], 0};
        result[i] = (char)strtol(tmp, NULL, 16);
    }

    printf("%s converted to %s\n", buf, result);
    free(result);

    return 0;
}

C++ 31 Jan 2010 11:23 pm

Snippet: Pointer Usage: Polymorphism

//tinodidriksen.com/uploads/code/cpp/pointer-polymorphism.cpp

#include <iostream>

struct A {
    virtual void foo() {
        std::cout << "A::foo()" << std::endl;
    }
    virtual ~A() {
    }
};

struct B : public A {
    void foo() {
        std::cout << "B::foo()" << std::endl;
    }
};

int main() {
    A *a = new A;
    a->foo();
    delete a;

    a = new B;
    a->foo();
    delete a;
}

C++ 04 Oct 2009 03:21 pm

C++ Map Speeds, MSVC++ Edition

(There is also a GNU g++ Edition of these performance tests, and a newer std::set comparison.)

Here is a complete test of MSVC++ map speeds, using same code as my previous map speed test: timemap.cpp with cycle.h.

The compilers are Microsoft Visual C++ 2008 Express as VC9 and Microsoft Visual C++ 2010 Beta as VC10. The containers are std::map, stdext::hash_map, std::tr1::unordered_map, and boost::unordered_map, each with _SECURE_SCL enabled and disabled.

Continue Reading »

C++ 09 Jul 2009 11:43 pm

C++ Map Speeds, GNU g++ Edition

(There is also an MSVC++ Edition of these performance tests, and a newer std::set comparison.)

While testing whether anything would break by switching to std::tr1::unordered_map for CG-3, I noticed it ran a consistent 15% faster. So, for my own curiousity, I threw together this little speed test: timemap.cpp with cycle.h.

Should be compiled with GCC g++ of at least version 4.3 to have TR1, and with -O2 or higher; -O will not optimize the hash maps sufficiently.

Now, that is obviously a naive test. Maps of integer to integer is a trivial case, but it is also a case I use often in CG-3 so I figured it would suit fine for a test.
Continue Reading »

« Previous Page