0

I would like to convert an UIImage into unsigned char*. First I convert UIImage into NSData, then NSData to unsigned char*. I use the following method to convert NSData to unsigned char*:

unsigned char *binaryData = (unsigned char *)[imageData bytes];

The problem is that there are many many bytes in imageData (which is an NSData), but after the method, the binaryData is just 0x75e8000. I have no idea why. Could anybody help me out there? And can you suggest me one way to correctly convert NSData to unsigned char*?

Thanks in advance!!!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jenny Cheung
  • 301
  • 2
  • 5
  • 12
  • 2
    How are you checking the "contents" of binaryData? By default, the debugger will treat that as a C string, which will stop printing when it reaches a NULL byte. Alternatively, that value could be the pointer itself, but that would change every time you ran the code. – Avi Nov 19 '15 at 03:56

2 Answers2

2

I don't think you understand what a C array is. It is represented as a pointer into the start of the array. Your 0x75e8000 is the start of the array. But the array contains no information about its length; how much more data there may be is unknown.

Also, you may not understand what the bytes method is. The bytes method does not "convert" anything, nor does it generate a copy; it merely provides a pointer into the NSData itself. As long as the NSData exists, the bytes points at it, but treats it as a const void* (which you are casting to an unsigned char*), suitable for handing to a C function.

So, the length of the C array, which you would need to tell any C function that uses this information, must be obtained separately; it is the length of the NSData object. And if you want to extract the data, as a copy, into a separate C array, then call getBytes:length:.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

Nothing is more explicit than just posting code.

    - (void)viewDidLoad {

        [self test];
    }

    - (void)test {

        // Put a picture named "test.jpg" in your app bundle
        NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        char buffer[data.length];

        // Print them out
        [data getBytes:buffer length:data.length];
        for (int i = 0; i < data.length; i++) {
            printf("0x%02x ",(unsigned char)buffer[i]);
        }
    }