将字符串转换为有符号整型
我想将字符串转换为有符号整数。以下是要求。我已将十六进制值作为字符串存储在缓冲区中。现在我想将该值转换为有符号整数。
buf = "fb869e"
将其转换为有符号整数。所以 o/p 应该是 -293218。但是当我尝试使用 strtol 进行转换时,我得到 16483998。那么我应该做什么?
I want to convert a string into a signed int. Following is the requirement. I have stored hex value as a string in buffer. Now I want to convert that value into signed int.
buf = "fb869e"
Convert this into signed int. So o/p should be -293218. but when I'm trying to convert using strtol I'm getting 16483998. So what I should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
十六进制数
0xfb869e
不是负数。内置数字转换函数不会将其转换为负值,因为它的值为正数。您所说的是,这是 24 位 2 补码负数的无符号十六进制等价物,并且您想要该数字。获得该值的方法是将其转换为正数,然后使用计算将其转换为等价的 24 位 2 补码:
The hexadecimal number
0xfb869e
is not negative. The inbuilt number conversion functions will not convert it to a negative value, since its value is positive.What you are saying is that this is the unsigned hexadecimal equivalent of a 24-bit 2s complement negative number, and you want that number. The way to get that is to convert it to the positive number, then use calculations to convert it to the 24-bit 2s complement equivalent:
其他人建议使用
strtol()
。我只想提到 sscanf() 作为替代方案,例如:Others have suggested
strtol()
. I just want to mentionsscanf()
as an alternative, eg:strtol 将字符串转换为长整数
输出是正确的,它将是 16483998
并且如果您使用 atoi,当它将字符串转换为整数时,如果超出可表示值的范围,则返回正确的值,INT_MAX 或 INT_MIN 。
strtol converts string to long integer
The output is correct and it will be 16483998
And if you use atoi, while it converts to string to integer, the correct value if out of the range of representable values, INT_MAX or INT_MIN is returned.
为什么 0x00fb869e 应该是负数?您应该必须提供数字系统的基础,甚至可以判断一种格式的值在另一种格式中是否为负数
why should 0x00fb869e be a negative number? you should have to provide the base of your number system, to even be allowed to tell, whether a value in one format is a negative in another format
作为有符号整数,必须设置高位才能产生负数。由于给定数字的高位未设置,因此它必须是正数。
如果您希望该数字被视为 24 位数字,则必须将第 23 位填充到剩余的高位。这是一种方法:
As a signed integer, the high bit must be set to produce a negative number. Since the high bit of the given number isn't set, it must be positive.
If you want the number to be treated as a 24-bit number, you'll have to pad bit 23 out to the remaining high-bits. Here's one way to do it:
使用
strtol
将string
转换为long
整数。Use
strtol
which convertsstring
to along
integer.尝试下面的代码块,它对我有用。
Try below block of code, its working for me.