3

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

NSData* data = UIImagePNGRepresentation(img);
2
  • try this answer I think it will help you Commented Nov 5, 2011 at 9:58
  • You read the documentation for NSData. Everything else is just simple C code. Commented Jun 30, 2013 at 11:32

2 Answers 2

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 ;)

Sign up to request clarification or add additional context in comments.

1 Comment

or this way UInt8 *bytes = (UInt8 *)[data subdataWithRange:(NSRange){0,length}].bytes
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;
}

1 Comment

xcode 6 throws an error for me initialising 'unsigned char' with an expression of incompatible type const void. ... unsigned char byteFromArray = data.bytes[i];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.