[英]Unsigned wrapped around Integer to the 'actual' value C
測試中給了我一些數字,這些數字存儲為Contiki使用的無符號整數,用C實現(即,無符號整數),並且基本上不斷地加上正數。
他們現在是負面的,所以我假設他們被纏住了。 有人要求我獲取整數的“實際”假定值。
所有整數都在32768以下,因此我假設它以2 ^ 15環繞。 許多整數都接近-32768,所以我假設它從32768變為-32768。
所以基本上,如果我得到一個像-23000這樣的整數,它的實際假定值(以我為例)為(32768 +(32768-23000))= 42536?
這個對嗎?
編輯:
很清楚,我說的是contiki中定義的uipstats_t類型。 像這樣:
struct uip_stats {
struct {
uip_stats_t recv; /**< Number of received packets at the IP
layer. */
uip_stats_t sent; /**< Number of sent packets at the IP
layer. */
uip_stats_t forwarded;/**< Number of forwarded packets at the IP
layer. */
uip_stats_t drop; /**< Number of dropped packets at the IP
layer. */
uip_stats_t vhlerr; /**< Number of packets dropped due to wrong
IP version or header length. */
uip_stats_t hblenerr; /**< Number of packets dropped due to wrong
IP length, high byte. */
uip_stats_t lblenerr; /**< Number of packets dropped due to wrong
IP length, low byte. */
uip_stats_t fragerr; /**< Number of packets dropped because they
were IP fragments. */
uip_stats_t chkerr; /**< Number of packets dropped due to IP
checksum errors. */
uip_stats_t protoerr; /**< Number of packets dropped because they
were neither ICMP, UDP nor TCP. */
} ip;
它們在我的平台上定義為:
typedef unsigned int uip_stats_t;
它們已被記錄並呈現給我,如下所示:
PRINTA("UIP STATS. recv %d sent %d drp %d\n",
uip_stat.ip.recv,
uip_stat.ip.sent,
uip_stat.ip.drop);
我已經按上述代碼打印了數字。
在輸出PRINTA()
語句中,您將%d
用作格式說明符。
假設它是printf()
系列的包裝, %d
僅用於有符號整數(*) ; 要輸出無符號整數(*) ,應改用%u
說明符。
(*):在這種情況下,我的意思是類型為int
和unsigned int
(或等效形式)的變量。 對於具有其他大小的整數類型,輸出說明符是不同的。
為了說明這一點,請考慮以下示例:
int main() {
int a;
unsigned int b;
a = -1;
b = *(unsigned int *)&a;
printf("%d %u\n", b, b);
return 0;
}
在我的平台上,輸出:
-1 4294967295
為了進一步了解這一點,您不妨閱讀一下Twos的補語 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.