Linux内核使用的字符串转整形数和16进制数

kstrtouint和kstrtou8函数定义在文件kernel/lib/kstrtox.c中,原形如下:

	233 /**
	234  * kstrtoint - convert a string to an int
	235  * @s: The start of the string. The string must be null-terminated, and may also
	236  *  include a single newline before its terminating null. The first character
	237  *  may also be a plus sign or a minus sign.
	238  * @base: The number base to use. The maximum supported base is 16. If base is
	239  *  given as 0, then the base of the string is automatically detected with the
	240  *  conventional semantics - If it begins with 0x the number will be parsed as a
	241  *  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
	242  *  parsed as an octal number. Otherwise it will be parsed as a decimal.
	243  * @res: Where to write the result of the conversion on success.
	244  *
	245  * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
	246  * Used as a replacement for the obsolete simple_strtoull. Return code must
	247  * be checked.
	248  */
	249 int kstrtoint(const char *s, unsigned int base, int *res)
	250 {
	251         long long tmp;
	252         int rv;
	253
	254         rv = kstrtoll(s, base, &tmp);
	255         if (rv < 0)
	256                 return rv;
	257         if (tmp != (long long)(int)tmp)
	258                 return -ERANGE;
	259         *res = tmp;
	260         return 0;
	261 }
	262 EXPORT_SYMBOL(kstrtoint);


	294 int kstrtou8(const char *s, unsigned int base, u8 *res)
	295 {
	296         unsigned long long tmp;
	297         int rv;
	298
	299         rv = kstrtoull(s, base, &tmp);
	300         if (rv < 0)
	301                 return rv;
	302         if (tmp != (unsigned long long)(u8)tmp)
	303                 return -ERANGE;
	304         *res = tmp;
	305         return 0;
	306 }

s是输入字符串,base可以是10(10进制)或16(16进制),或者是0自动识别:
base 为10,则字符串转换成10进制数,使用kstrtoint函数;
base 为16,则字符串转换成16进制数,使用kstrtou8函数;

res为存放转换后的数值;

当没有错误时返回值是0。

具体使用demo:

static ssize_t gpio_led_store(struct device *dev, struct device_attribute *attr,
						const char *buf, size_t size)
{
	int val;
	int ret;

	ret = kstrtoint(buf, 10, &val); //输入一个字符然后转换成10进制整形数

        if (ret) {
		printk("%s: kstrtoint error return %d\n", __func__, ret);
		return -1;
        }

	if (val== 1) { //如果echo 1 到节点则调用

		printk("-czd-: _%s_ :gpio pull up\n", __func__);
		gpio_direction_output(gpio_led, val); //设置GPIO电平为高电平

	} else if (val == 0) { //如果echo 0 到节点则调用

		printk("-czd-: _%s_ :gpio pull down\n", __func__);
		gpio_direction_output(gpio_led, val); //设置GPIO电平为低电平

	} else {

		printk("I only support 0 or 1 to ctrl led\n");

	}
	return size;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零意@

您的打赏将是我继续创作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值