C++ 31 Jan 2010 23:31:34

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 23:29:24

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 23:23:58

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;
}

« Previous Page