简体   繁体   中英

Equivalent for DataOutputStream of Java in Objective C

I am currently working on a Project which is in Objective C.

I need to use Functions of Java class DataOutputStream like writeChars , writeLong , flush and some functions of ByteArrayOutputStream Class.

Specifically, what can I use in Objective C which has the same functionality as the DataOutputStream and ByteArrayOutputStream class?

This is the code i need to convert into Objective C.

public static byte[] getByteArray(String key, long counter) throws IOException
{

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    if (key != null)
    {
        dos.writeChars(key);
    }
    dos.writeLong(counter);
    dos.flush();
    byte[] data = bos.toByteArray();
    return data;
}
NSLog();

the above method takes string and objects as arguments. As,

NSLog(@"Hi this is demo of string printing.");

NSLog(@"Hi this is integer %d",intValue);//this is like printf isnt it?

EDIT:

Either %b, or convert it into NSData object and then print using %@. Obj-c uses %@ for all kind of object.

unsigned int a = 0x000000FF;
NSLog(@"%x", a);//prints the most significant digits first

What you want is convert primitive data types into raw bytes.

NSMutableData* dataBuffer = [NSMutableData data]; //obj-c byte array

long long number = 123456LL; //note that long long is needed in obj-c to represent 64bit numbers
NSData* numberData = [NSData dataWithBytes:&number length:sizeof(number)]; 
[dataBuffer appendData:numberData];

NSString* text = @"abcdefg";
const char* rawText = [text cStringUsingEncoding:NSUTF8StringEncoding]; //java uses utf8 encoding
NSData* textData = [NSData dataWithBytes:rawText length:strlen(rawText)];
[dataBuffer appendData:textData];

return dataBuffer;

No flush() is necessary (I believe in Java is not neccessary with ByteArrayOutputStream either)

This is a bit simplified, note that when Java writes a string, the first two bytes are always the string length. Java also writes numbers in Big Endian. We are writing them in system byte-order. That shouldn't be a problem if you don't want to send the binary data to other devices.

You can switch byte order using utilities in CFByteOrderUtils.h or you can get the number in Big Endian directly by the following:

- (NSData*)bytesFromLongLong:(long long)number {
    char buffer[8];

    for (int i = sizeof(buffer) - 1; i >= 0; i--) {
        buffer[i] = (number & 0xFF);
        number >> 8; 
    }

    return [NSData dataWithBytes:buffer length:sizeof(buffer)]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM