c++ 解決無法列印uint8_t 型別變數的問題
阿新 • • 發佈:2020-12-10
將uint8_t 轉化為unsigned 型別
使用一元運算子+(和- 運算子對應)
測試程式碼如下
#include <cstdint> #include <iostream> #include <typeinfo> int main() { std::uint8_t uint8_num = 10; std::cout << "uint8_t num is " << uint8_num << std::endl; //無法列印 std::cout << "after cast to unsigned,uint8_t num is " << unsigned(uint8_num) << std::endl; //能正常列印 std::cout << "with a unary + operator,uint8_t num is " << +uint8_num << std::endl; //能正常列印 std::cout << "type of '+uint8_num' is " << typeid(+uint8_num).name() << std::endl; return 0; }
執行結果如下
可見使用+運算子的原理也是進行型別轉換(把uint8_t 轉為 int)
補充知識:C 語言printf列印各種資料型別的方法(u8/s8/u16/s16.../u64/double/float)(全)
首先必須知道u8,s8等資料型別的定義:
typedef signed char s8; typedef unsigned char u8; typedef signed short s16; typedef unsigned short u16; typedef signed int s32; typedef unsigned int u32; typedef signed long long s64; typedef unsigned long long u64;
與體系結構相關的,定義在include/linux/type.h檔案中:
/* bsd */ typedef unsigned char u_char; typedef unsigned short u_short; typedef unsigned int u_int; typedef unsigned long u_long; /* sysv */ typedef unsigned char unchar; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; #ifndef __BIT_TYPES_DEFINED__ #define __BIT_TYPES_DEFINED__ typedef __u8 u_int8_t; typedef __s8 int8_t; typedef __u16 u_int16_t; typedef __s16 int16_t; typedef __u32 u_int32_t; typedef __s32 int32_t; #endif /* !(__BIT_TYPES_DEFINED__) */ typedef __u8 uint8_t; typedef __u16 uint16_t; typedef __u32 uint32_t; #if defined(__GNUC__) typedef __u64 uint64_t; typedef __u64 u_int64_t; typedef __s64 int64_t;
對於各種資料型別的列印方式總結如下如下:
資料型別 | 列印格式 |
---|---|
u8 | %d |
s8 | %d |
u16 | %d or %hu |
s16 | %d or %hd |
u32 | %u |
s32 | %d |
u64 | %llu |
s64 | %lld |
int | %d |
unsigned int | %u |
short int | %d or %hd |
long | %ld |
unsigned long | %lu |
long long | %lld |
unsigned long long | %llu |
char | %c |
char * | %s |
bool (#define stdbool.h) | %d |
unsigned int/int------>十六進位制 | %0x |
unsigned long/long---->十六進位制 | %0lx |
long long/unsigned long long ----->十六進位制 | %0llx |
unsigned int/int------>八進位制 | %0o |
unsigned long/long---->八進位制 | %0lo |
long long/unsigned long long ----->八進位制 | %0llo |
float | %f |
double | %f or %lf |
科學技術型別(必須轉化為double型別) | %e |
限制輸出欄位寬度 | %x.yf (x:整數長度,y:小數點長度) |
待解問題,在linux kernel裡面也有使用bool來定義變數,檢視code,定義如下:
typedef _Bool bool;
但是並沒有真正找到具體定義在何處,待解。
下面是stdbool.h的source code:
#define _STDBOOL_H #ifndef __cplusplus #define bool _Bool #define true 1 #define false 0 #else /* __cplusplus */ /* Supporting _Bool in C++ is a GCC extension. */ #define _Bool bool #if __cplusplus < 201103L /* Defining these macros in C++98 is a GCC extension. */ #define bool bool #define false false #define true true #endif #endif /* __cplusplus */ /* Signal that all the definitions are present. */ #define __bool_true_false_are_defined 1 #endif /* stdbool.h */
也大致解釋了linux kernel bool type了。
以上這篇c++ 解決無法列印uint8_t 型別變數的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。