3

Please any one guide me how to create bytes array from nsdata here is my code for createing nsdata

NSData* data = UIImagePNGRepresentation(img);
Manish Jain
  • 865
  • 3
  • 13
  • 28
  • try [this](http://stackoverflow.com/questions/724086/how-to-convert-nsdata-to-byte-array-in-iphone/724365#724365) answer I think it will help you – salahy Nov 05 '11 at 09:58
  • You read the [documentation for NSData](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html). Everything else is just simple C code. – Hot Licks Jun 30 '13 at 11:32

2 Answers2

3

If you only want to read them, there's a really easy method :

unsigned char *bytes = [data bytes];

If you want to edit the data, there's a method on NSData that does this.

// Make your array to hold the bytes
NSUInteger length = [data length];
unsigned char *bytes = malloc( length * sizeof(unsigned char) );

// Get the data
[data getBytes:bytes length:length];

NB Don't forget - if you're copying the data, you also have to call free(bytes) at some point ;)

deanWombourne
  • 38,189
  • 13
  • 98
  • 110
2

Here is fastest way (but pretty danger) to get array:

unsigned char *bytesArray = data.bytes;
NSUInteger lengthOfBytesArray = data.length;

before trying to get byte#100 you should check lengthOfBytesArray like:

if (lengthOfBytesArray > 100 + 1)
{
    unsigned char byteWithOffset100 = bytesArray[100];
}

And another safe and more objc-like way:

- (NSArray*) arrayOfBytesFromData:(NSData*) data
{
    if (data.length > 0)
    {
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:data.length];
        NSUInteger i = 0;

        for (i = 0; i < data.length; i++)
        {
            unsigned char byteFromArray = data.bytes[i];
            [array addObject:[NSValue valueWithBytes:&byteFromArray 
                                            objCType:@encode(unsigned char)]];
        }

        return [NSArray arrayWithArray:array];
    }

    return nil;
}
holodnyalex
  • 761
  • 5
  • 8
  • xcode 6 throws an error for me initialising 'unsigned char' with an expression of incompatible type const void. ... unsigned char byteFromArray = data.bytes[i]; – johndpope Feb 06 '15 at 23:00