考慮下面的代碼:
// First, we get the C-string (NULL-terminated array of bytes) out of NSString.
const char *cString = [command UTF8String];
// The length of C-string (a number of bytes!) differs terribly from
// NSString length (number of characters! Unicode characters are
// of variable length!).
// So we get actual number of bytes and clamp it to the buffer
// size (so if the command string occasionally gets larger than our
// buffer, it gets truncated).
size_t byteCount = MIN(BUFFER_SIZE - 4,
[command lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
// Now we're using C type conversion to reinterpret the buffer as a
// pointer to int32_t. The buffer points to some memory, it's up to us
// how to treat it.
*(int32_t *)buffer = byteCount;
// And finally we're copying our string bytes to the rest of the buffer.
memcpy(buffer + 4, cString, byteCount);
有這個代碼一個警告 - 它採用主機字節順序存儲uint32_t
變量,因此,如果你通過網絡傳遞這個緩衝區,通常是一個好主意,使你的字節順序是固定的(網絡歷史上採用大字節序,儘管大多數計算機現在是小端)。
要解決的字節順序只需更換線
*(int32_t *)buffer = byteCount;
與
*(int32_t *)buffer = htonl(byteCount);
而且不要忘了字節順序轉換回處理其他計算機上該緩衝區的時候!
看來你的答案對我來說很重要,但是我很難理解它的實際功能。你介意可擴展的例子嗎?比如說我想把一個消息的長度附加到緩衝區的末尾,並在那之後追加消息,我該如何去做這件事? –
@ cnh1991我已將評論添加到我的代碼中。希望能幫助到你。 – iHunter
@ cnh1991如果您想在緩衝區的最後寫入長度,則會執行以下代碼:'*(uint32_t *)(buffer + 1020)= byteCount'。它重新解釋'buffer + 1020',例如作爲指向'uint32_t'的指針,從'buffer'開始的1020個字符。 – iHunter