从 unsigned long int 转换为signed int,反之亦然
我想将一个有符号的 int 传递给 gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n)
。我传递的有符号整数大于或等于零。该函数将返回 0
和 n
之间的数字,因此如果我向其传递一个正有符号 int,它将返回有符号 int 范围内的内容。然后我想将返回值存储在有符号整数中。对于明显的预期行为,最干净的方法是什么?我在 64 位 Linux 机器上使用 64 位编译器。
更新 抱歉,各位。请忽略。我的代码的问题实际上在其他地方。我误解了 gdb 的输出。
I would like to pass a signed int to gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n)
. The signed int that I'm passing is greater than or equal to zero. The function will return a number between 0
and n
, so if I pass it a positive signed int, it will return something that is in the range of a signed int. I then want to store the return value in a signed int. What's the cleanest way to do this with the obvious expected behaviour? I'm on a 64-bit compiler on a 64-bit Linux machine.
Update
Sorry, folks. Please ignore. The problem with my code was actually elsewhere. I misinterpreted the output of gdb
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
开头:
编译器可能会警告不安全的缩小转换,因此更改为:
或者为了安全:
这些行可以包含在辅助函数中:
在任何情况下,测试您的输入通常比测试您所依赖的函数的输出更有用开启,并且如果您信任
gsl_rng_uniform_int
,那么测试输入就足够了。[编辑:哇,谷歌索引非常积极。我只是搜索以检查
gsl_rng_uniform_signed
是否已经是一个函数,然后发现了我自己。]Start with:
Likely the compiler will warn about an unsafe narrowing conversion, so change to:
Or for safety:
Those lines could be wrapped in a helper function:
In any case testing your input is typically more useful than testing the output of functions you rely on, and if you trust
gsl_rng_uniform_int
then testing the input is sufficient.[Edit: wow, Google indexes SO really aggressively. I just searched to check that
gsl_rng_uniform_signed
isn't already a function, and found myself.]如果函数需要
unsigned long
,您可以毫无问题地传递unsigned long
、unsigned int
、unsigned Short
和unsigned char
,标准保证了这一点。如果您传递一个
signed
但负数int
,您将不会获得正确的结果,因为它会被函数计算为一个非常大的int。最好的方法是在传递之前检查有符号 int 是否为
>= 0
。我希望我正确理解你的问题。
If the function expects an
unsigned long
you can pass with no problem anunsigned long
,unsigned int
,unsigned short
andunsigned char
, the standard guarantees that.If you pass a
signed
but negativeint
, you will not obtain the correct results, since it will be evaluated to a very big int by the function.The best way is to check if it the signed int is
>= 0
before passing it.I hope I understood your question correctly.