簡體   English   中英

與Objective C中Java的DataOutputStream等效

[英]Equivalent for DataOutputStream of Java in Objective C

我目前正在開發目標C中的一個項目。

我需要使用Java類DataOutputStream函數,例如writeCharswriteLongflushByteArrayOutputStream類的某些函數。

具體來說,我可以在具有與DataOutputStreamByteArrayOutputStream類相同功能的Objective C中使用什么?

這是我需要轉換為目標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();

上面的方法將字符串和對象作為參數。 如,

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

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

編輯:

%b,或者將其轉換為NSData對象,然后使用%@打印。 Obj-c對所有類型的對象使用%@。

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

您需要將原始數據類型轉換為原始字節。

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;

無需flush() (我相信ByteArrayOutputStream也不需要Java)

這有點簡化,請注意,當Java編寫字符串時,前兩個字節始終是字符串長度。 Java還使用Big Endian編寫數字。 我們以系統字節順序編寫它們。 如果您不想將二進制數據發送到其他設備,那應該不成問題。

您可以使用CFByteOrderUtils.h實用程序來切換字節順序,也可以通過以下方式直接在Big Endian中獲取數字:

- (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)]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM