为什么printf为unsigned int显示负值? [英] Why does printf show negative values for unsigned int?

查看:767
本文介绍了为什么printf为unsigned int显示负值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
带负值的无符号长

Possible Duplicate:
Unsigned long with negative value

我已经编写了一个内核模块,该模块可以中断任何系统调用,打印其当前的user_id并输入传递给系统调用函数的参数.其中之一是sys_ioctl(),如下所示:

I have written one kernel module which interrupts any system call, prints its current user_id and input parameters passed to the system call function. Among them, one is sys_ioctl() as below:

asmlinkage long sys_ioctl(unsigned int fd, unsigned int cmd,unsigned long arg);

表示所有输入参数均为无符号整数.

which means all input parameters are unsigned int numbers.

但是当我打印输入参数时,我得到以下输出:

But when I print input parameters, I get the following output:

 fd=21, cmd=-1072143871 and arg=3202983648 
 fd=21, cmd=-1072143871 and arg=3202983648 
 fd=21, cmd=-1072143871 and arg=3202983648 
 ----------

这是我的函数定义:

asmlinkage long our_sys_ioctl(unsigned int fd ,  unsigned int cmd , unsigned long arg)
{
    uid_t gtuid ;
    gtuid = getuid_call();
    printk ("our_sys_ioctl ---> uid = %d with fd=%i, cmd=%i and arg=%lu \n ", gtuid, fd, cmd, arg);
    return original_call_ioctl(fd , cmd , arg);
}

知道cmd值为什么为负以及这些值是什么意思吗?

Any idea why cmd value is negative and what these values mean?

推荐答案

使用%i打印cmd 时,您正在像@Mario先前那样将其投射到signed int .这就是为什么它是负面的.

When you use %i to print the cmd you are casting it to signed int as @Mario previously guessed. This is why it is negative.

您需要使用%u进行打印,以使其保持unsigned int

You need to use %u to do the printing for it to remain an unsigned int

d或i-带符号的十进制整数

d or i - Signed decimal integer

u-无符号十进制整数

u - Unsigned decimal integer

(来自: http://www.cplusplus.com/reference/cstdio/printf/)

这将按预期工作.

printk ("our_sys_ioctl ---> uid = %d with fd=%i, cmd=%u and arg=%lu \n ", gtuid, fd, cmd, arg);
                                                    ^^^^

这篇关于为什么printf为unsigned int显示负值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆