Sunday, March 16, 2008

Data type and byte order conversions for NSData using the STL

We've been spoiled working in Python's numpy array library. Converting data types or byte order for numeric data in a numpy array is trivial (thanks to the work of numpy's authors of course). When we're in Objective-C land, the inability to change data types or byte orders on NSData instances is frustrating. So we've written a short C++ header that provides templated functions for converting the data type and/or byte order of numeric data stored in NSData/NSMutableData instances. I think it might be useful for others who don't want to (re)learn C++ and the STL. Writing code in Objective-C to accomplish the same functionality is a mess of if/then/else or switch statements. Every job has a tool and C++ templates seem to be the best tool for this job (numpy's authors have a similar solution using a code generator to keep things all in C).

For the brave and or insterested, take a look at NumericDataTypeConversions.h  (BSD license). Bug reports or patches are welcome. Since it's a C++ header, any Objetive-C file that includes it will have to have the .mm extension (or otherwise ensure that the file is compiled as Objective-C++). Happy coding.