1

i want to create a byte array in objective c, i am not able to find equivalent code of java's ByteArrayOutputStream and DataOutputStream. for eg..

ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeLong(counter); //counter is a long data type for eg 1165620611
dos.flush();
byte[] data = bos.toByteArray();
return data;

this code actually returns eight byte array...Here's the output in java [0,0,0,0,69,121,-11,-125]

this is what i want exactly in objective c..

3 Answers 3

7
// #1 long to char array
long l = 1165620611;
char bytes[sizeof(long)];
memcpy(bytes,&l,sizeof(l));

// #2 char array to nsdata
int size = sizeof(bytes)/sizeof(char);
NSData *data = [NSData dataWithBytes:bytes length:size];

// #3 nsdata to char array
char buffer[size];
[data getBytes:buffer length:size];

// #4 prints char array: 0 0 0 0 69 121 -11 -125
while (0<size--) {
    NSLog(@"%d",buffer[size]);
}

NSData is not needed at all, you can skip steps #2 and #3.

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

Comments

5

use char buff[] array in objective - c

Comments

1

You can use NSData & NSMutableData classes for this.

NSData and its mutable subclass NSMutableData provide data objects, object-oriented wrappers for byte buffers. Data objects let simple allocated buffers (that is, data with no embedded pointers) take on the behavior of Foundation objects.

NSData creates static data objects, and NSMutableData creates dynamic data objects. NSData and NSMutableData are typically used for data storage and are also useful in Distributed Objects applications, where data contained in data objects can be copied or moved between applications.

The size of the data is subject to a theoretical limit of about 8 ExaBytes (in practice, the limit should not be a factor).

NSData is “toll-free bridged” with its Core Foundation counterpart, CFDataRef. See “Toll-Free Bridging” for more information on toll-free bridging.

Comments

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.