Showing posts with label convert. Show all posts
Showing posts with label convert. Show all posts

Thursday, July 23, 2009

Homemade recipe

This is another example of how simple "homemade" approach significantly outperforms patented generic methods. How often you needed to convert byte array into String object and vice versa? The recommended methods always require the name of Charset. Since in my case the charset is always UTF-8, I hardcoded it.
When converting from byte array to String, something like following can be used:
final static String b2s_recommended(byte[] bb) {
    try {
        return new String(bb, 0, bb.length, "UTF-8");
    } catch(Exception ex) {
        throw new RuntimeException(ex.getMessage());
    }
}
   
   

When converting from String to byte array something like following can be used:
final static byte[] s2b_recommended(String s) {
    try {
        return s.getBytes("UTF-8");
    } catch(Exception ex) {
        throw new RuntimeException(ex.getMessage());
    }
}
   
   

Corresponding "homemade" methods that don't pretend to be generic, can look like following:
final static String b2s_homemade(byte[] bb) {
    char[] cc = new char[bb.length];
    for (int i = 0; i < bb.length; ++i) {
        cc[i] = (char) bb[i];
    }
    return new String(cc);
}
   
final static byte[] s2b_homemade(String s) {
    byte[] bb = new byte[s.length()];
    for (int i = 0; i < bb.length; ++i) {
        bb[i] = (byte) s.charAt(i);
    }
    return bb;
}
   

On my computer homemade b2s outperformed recommended one with factor of 4.2 . For the s2b the performance bust was 6.0 !

Thursday, April 23, 2009

Posting Code

This blog is about computers, programming and alike. So its essential for me to be able to post source code in descent form. In the case of Visual Studio the answer appeared obvious. My idea was to copy code to Windows clipboard, paste into wordpad, save as Rich Text Format file (*.rtf), convert to html and paste into blog editor.

The step that almost failed was converting from rtf to html. All free converters I was able to spot on the Web miserably failed. I even don't want to give links to the suckers. Well, I said almost. One converter worked good for me. The online one. Of course, its a hassle to use online stuff with all verifications etc., but for me its better than inferior quality of conversion. Check the quality for yourself:

// This is a comment
int main(int argc, char* argv[])
{
    cout << "Hello, RTF 2 HTML!" << endl;
    return 0;
}
   

I copied the html code from Firefox's View->Page Source window.
So, if you are curious, find the link to the converter below:
RTF to HTML Online
Another downside of the converter - bloating size of the resulting html. In the example above size changed from 516 bytes in rtf file to 1,698 bytes in the converted html file.