簡體   English   中英

將 int 轉換為 char 數組的最佳方法

[英]Optimal way to convert an int into a char array

int放入char數組的最佳方法(性能)是什么? 這是我當前的代碼:

data[0] = length & 0xff;
data[1] = (length >> 8)  & 0xff;
data[2] = (length >> 16) & 0xff;
data[3] = (length >> 24) & 0xff;

data是一個char數組(共享 ptr), lengthint

你在找 memcpy

char x[20];
int a;
memcpy(&a,x,sizeof(int));

您的解決方案也很好,因為它是endian safe

附注:-

盡管對於任何特定實現都沒有這樣的保證sizeof(int)==4

只需使用reinterpret_cast 像使用 int 指針一樣使用數據數組。

    char data[sizeof(int)];
    *reinterpret_cast<int*>(data) = length;

順便說一句, memcpy比這慢得多,因為它使用循環逐字節復制。
在整數的情況下,這只是一個簡單的賦值。

這是唯一的方法。 從理論上講,您可以使用memcpyreinterpret_cast但由於endians 的問題,您不能使用。

暫無
暫無

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

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