POCO中的資料型別和位元組序

2021-06-27 23:05:58 字數 2982 閱讀 3556

poco中的資料型別和位元組序

概要:固定長度的整數型別,位元組序轉換,和any/dynamicany型別

1、固定長度的整數型別

poco定義了固定長度的整數型別

#include "poco/types.h"

(自動包含在 poco/foundation.h 中)

分別是poco::int8, poco::int16, poco::int32, poco::int64

poco::uint8, poco::uint16, poco::uint32, poco::uint64

注意poco::intptr, poco::uintptr與指標(32位或64位)長度相等的整形

對於嵌入式**,如果你需要固定長度整數,請使用以上型別。

2、內建資料型別的長度

poco有兩個巨集定義,用來定義long型別和指標型別的長度。

poco_ptr_is_64_bit

這個巨集定義了指標是64位的

poco_long_is_64_bit

這個巨集定義了long型別是64位的

3、位元組序

poco提供了處理位元組序問題的工具,

根據當前主機的位元組序預定義了巨集

poco_arch_little_endian

這個巨集定義了低位元組序

poco_arch_big_endian

這個巨集定義了高位元組序

4、位元組序轉換

poco::byteorder類提供了位元組序轉換的靜態方法。

需要包含標頭檔案 #include "poco/byteorder.h"

對int16, uint16, int32, uint32, int64 and uint64,

intxx flipbytes(intxx value)

將資料型別從高位元組序轉換為低位元組序,或者相反。

intxx tobigendian(intxx value)

從主機位元組序轉換為高位元組序

intxx tolittleendian(intxx value)

從主機位元組序轉換為低位元組序

intxx frombigendian(intxx value)

從高位元組序轉換為主機位元組序

intxx fromlittleendian(intxx value)

從低位元組序轉換為主機位元組序

intxx tonetwork(intxx value)

從主機位元組序轉換為網路位元組序

intxx fromnetwork(intxx value)

從網路位元組序轉換為主機位元組序

記住,網路位元組序是高位元組序。

所有的轉換函式都定義為inline函式,因此效率比較高。不必要的轉換會在編譯時被優化。

以下是示例

#include "poco/byteorder.h"

#include using poco::byteorder;

using poco::uint16;

int main(int argc, char** argv)

三、any型別

包含標頭檔案 #include "poco/any.h"

poco::any型別可以容納任何內建的或自定義的資料型別

poco::any型別支援以型別安全(type-safe)的方式提取資料。

要從中提取實際資料,就必須知道資料型別,這就會用到

poco::anycast() 和 poco::refanycast() 函式模板。

程式示例:

#include "poco/any.h"

#include "poco/exception.h"

using poco::any;

using poco::anycast;

using poco::refanycast;

int main(int argc, char** argv)

catch (poco::badcastexception&)

return 0;

}

四、dynamicany型別

要包含標頭檔案 #include "poco/dynamicany.h"

poco::dynamicany型別可以容納以 dynamicanyholder 特殊化的任意型別資料。

poco::dynamicany 支援以型別安全的方式提取資料。

支援顯式或隱式的型別轉換(檢查資料範圍)。

dynamicany: convert() 和 extract() 的比較

t convert();

void convert(t& val);

operator t ()

都返回乙個複本,自動轉換,比any要慢。

const t& extract();

返回乙個引用常量,不是自動轉換,與any一樣塊。

dynamicany – 轉換規則

數值型不能出現資料丟失

小於0的數值不能被轉換成無符號型別

數值範圍(二進位制表示位數)不能在轉換中變小

從整型到浮點型的精度丟失可以被允許

字串合併可以被允許

程式示例:

#include "poco/dynamicany.h"

#include "poco/exception.h"

using poco::dynamicany;

int main(int argc, char** argv)

catch (poco::badcastexception&)

return 0;

}

any 和 dynamicany 的比較

any可以容納任何型別,但你必須容納資料的實際型別。

dynamicany能夠容納dynamicanyholder特殊化的任何型別。

顯式和隱式轉換的應用限制在一些固定型別之間,包括常見型別和std::string.

POCO 型別和位元組序

固定長度的整型,位元組序轉換,以及any dynamicany型別 固定長度整型 poco定義了一些固定長度的整型 include poco types.h poco foundation.h自動包含了以上檔案 poco int8,poco int16,poco int32,poco int64 p...

POCO 型別和位元組序

固定長度的整型,位元組序轉換,以及any dynamicany型別 固定長度整型 poco定義了一些固定長度的整型 include poco types.h poco foundation.h自動包含了以上檔案 poco int8,poco int16,poco int32,poco int64 p...

資料型別 位元組

字長 bit 位元組 8bit 字 32位處理器 4個位元組 32bit 半字 兩個位元組 16bit 運算子sizeof 不是函式,用於測量變數,資料型別的位元組長度 使用方法 sizeof 空格 變數名 或者sizeof 變數名 而測量資料時只能用後者。char 1個位元組 int 4個位元組 ...