views:

53

answers:

2

Hi there, I'm wondering if there is an Objective C equivalent to .Net's BitConverter.GetBytes() method.

For example, in C#, I can write something like this:

byte[] lengthPrefix = BitConverter.GetBytes(message.length);

What would the equivalent be in Objective C?

Some example code would be greatly appreciated.

Thanks in advance.

A: 

Sin Objective-C is C in its roots, you can use bitwise operators to accomplish something similar.

There is nothing on the COCOA/COCOA-TOUCH framework that will do that automatically for you (like's .NET's BitConverter).

Pablo Santa Cruz
+2  A: 

If you don't need a specific endian-ness:

unsigned char * lengthPrefix = (unsigned char *)&message.length;

Or, copy to a 32-bit buffer, if needed.

unsigned char lengthPrefixBuffer[4];
memcpy(lengthPrefixBuffer, &message.length, 4);
Jason
You are taking the address of a temporary returned integer. Does this compile? It might be in a register... `NSInteger length = message.length; unsigned char *lengthPrefix = (unsigned char*)`
calmh
+1 albeit not pretty should work (NSInteger == long) although I probably would have used sizeof just in case in the memcpy version.
Anders K.
There are a whole load of functions in Foundation to do endian related byte swapping.http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#jumpTo_181
JeremyP
Thanks for the answers! The following achieved the desired results:NSInteger length = [msgData length]; unsigned char *lengthPrefix = (unsigned char*)unsigned char lengthPrefixBuffer[4] = { 0, 0, 0, 0 };memcpy(lengthPrefixBuffer, (unsigned char *)lengthPrefix, 4);Thanks again, appreciated.