[英]C++ - Convert float to unsigned char array and then back to float
[英]Convert float to unsigned char array and print it
如何將float轉換為unsigned char *
數組並使用C ++打印? 我有下面的函數,當我嘗試打印時,得到的值是-0.000000
。
編輯:我有一個通用的接口,該接口具有返回unsigned char *
的功能。 每個實現此功能的類都處理不同類型的數據,即:字符串,浮點數,雙精度數,整數,字符。 最后,我希望所有返回unsigned char *
,不僅char *
因為我在乎每個功能將轉變為字節數組。
unsigned char * readRequest() {
float preCent = distanceCentimeters();
std::cout << "readRequest" << std::endl;
printf("%.10f ", preCent); // print correct result
unsigned char buf[4];
memcpy(buf, &preCent, sizeof(preCent));
printf(" %s ", buf); // print bytes
printf(" %lf ", buf); // prints -0.000000
std::cout << buf << std::endl; // print bytes
std::cout << "readRequest" << std::endl;
return buf;
}
unsigned char *readRequestArray;
readRequestArray = (unsigned char*) readRequest();
std::cout << readRequestArray << std::endl; // prints (null)
如何將float轉換為unsigned char *數組
取決於您要通過這種轉換實現的目標。
std::memcpy
將這些字節復制到unsigned char
數組中(也可以使用std::byte
): 例:
unsigned char buf[sizeof preCent];
std::memcpy(buf, &preCent, sizeof preCent);
...並打印
std::cout
) 例:
for(unsigned char c : buf)
std::cout << std::hex << (int)c;
請注意,轉換為非字符整數類型可以防止流將字節解釋為編碼字符。
如何[打印]實際浮點值
我想在將浮點值轉換為
unsigned char *
后打印unsigned char *
只需使用std::memcpy
反向將字節數組轉換回浮點數即可:
float converted_back;
std::memcpy(&converted_back, buf, sizeof converted_back);
std::cout << converted_back;
printf(" %lf ", buf); // prints -0.000000
%lf
要求參數的類型為double(或float將轉換為double)。 但是,您傳遞了類型為unsigned char[4]
buf
。 程序的行為是不確定的,因為您違反了此前提條件。
printf(" %s ", buf); // print bytes
%s
說明符要求參數為以null終止的字符串。 您的字符數組不是以null結尾的。 程序的行為是不確定的,因為您違反了此前提條件。 此外,數組的數據在字符編碼表示中毫無意義。
std::cout << buf << std::endl; // print bytes
字符流對插入的指針的要求與%s
printf說明符相同。 該行為是不確定的。
unsigned char buf[4]; ... return buf;
您返回一個指向本地數組的指針。 該數組在函數末尾被破壞,並且返回的指針懸空。
std::cout << readRequestArray << std::endl;
您將懸掛指針插入字符流。 您的程序的行為是不確定的。 即使它沒有懸空,它用來指向的數組(本地buf
)仍然不是以null終止的字符串。
使用%s
打印將不起作用,因為當您有一個指向字節數組的char *
指針時,它期望一個char *
指向一個以空終止的字符串。 使用%lf
也不起作用,因為它需要double
,並且char *
與之不兼容。 這兩個都調用了不確定的行為 。
如果要打印存儲在buf
的字節表示形式,則需要單獨打印每個字符的值。
unsigned char buf[sizeof(preCent)];
memcpy(buf, &preCent, sizeof(preCent));
for (size_t i=0; i<sizeof(preCent); i++) {
printf("%02x ", buf[i]);
}
printf("\n");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.