Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective c - How to convert nsdata to byte array [duplicate]

I am working with UIImage conversion to NSData. And I want to convert NsData to Byte Array and post that Byte array to server with the help of json Parser.

If i am passing following type of static string to server it accept and store. Following is just example string syntax. i want follwoing type of byte array to post data to server.

[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,96,0,96,0,0,255,219,0,67,0,8,6,6,7,6,5,8,7,7,7,9,9,8,10,12,...]

For above result i am converting image to data as following:

UIImage *image = [UIImage imageNamed:@"image.png"];
NSData *data = UIImagePNGRepresentation(image);

Now i want to convert NSdata to byte array for that i am using following code:

NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
free(byteData)

and i also store this to NSdata. but cant get about result. I also typed about code with looping but every time it gives aPNG as result.

Am i doing any thing wrong in the above code?

Please provide me some help and also request to provide any help for this.

Thanks in advance.

like image 590
Hrushikesh Betai Avatar asked Dec 21 '22 08:12

Hrushikesh Betai


1 Answers

I'm not 100% sure this is what you are looking for or not. Try:

UIImage *image = [UIImage imageNamed:@"image.png"];
NSData *data = UIImagePNGRepresentation(image);
NSUInteger len = data.length;
uint8_t *bytes = (uint8_t *)[data bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:len * 3];
[result appendString:@"["];
for (NSUInteger i = 0; i < len; i++) {
    if (i) {
        [result appendString:@","];
    }
    [result appendFormat:@"%d", bytes[i]];
}
[result appendString:@"]"];

Is this what you need?

like image 76
rmaddy Avatar answered Jan 05 '23 19:01

rmaddy