Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: How to create a method that will return a UInt8 array from an int

Tags:

objective-c

I need to create an Objective-C method that converts an int into a byte array. In this instance, I can't use NSArray as a return type, it must be an UInt8 array. I've written a simple method to do this, but it has errors during compile and tells me that I have incompatible return types. Here is the code snippet. Any ideas?

 - (UInt8[])ConvertToBytes:(int) i 
{

     UInt8 *retVal[4];

     retVal[0] = i >> 24;
     retVal[1] = i >> 16;
     retVal[2] = i >> 8;
     retVal[3] = i >> 0;

     return retVal;
}
like image 649
Adam Avatar asked Dec 02 '22 05:12

Adam


1 Answers

Return the value in a struct. You cannot return C-style arrays from C functions, and this also means that you cannot return them from Objective-C methods either. You can return a struct though, and structs are allowed arrays as members.


// in a header
typedef struct
{
    UInt8 val[4];
} FourBytes;


// in source
- (FourBytes) convertToBytes:(int) i
{
     FourBytes result = { i >> 24, i >> 16, i >> 8, i };
     return result;
}



- (void) someMethod
{
    FourBytes test = [someObject convertToBytes:0x12345678];
    NSLog ("%d, %d, %d, %d", test.val[0], test.val[1], test.val[2], test.val[3]);
}

like image 98
dreamlax Avatar answered May 19 '23 08:05

dreamlax