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.

1 comment:

Jorge Juan said...

Hi Barry. Thanks for sharing this methods. I need to create an NSData object from a vector, and found that your code does exactly that. However, not being that fluent in C++ I'm at a loss on how to use it. Could you share an example? I'm specifically interested in the numeric_data_to_vector and vector_to_numeric_data methods.

Also, if you could give me some pointers on how to modify this methods for 2D vectors (i.e. vector<vector<int> >) that would be awesome!