[英]Converting from unsigned long int to signed int and vice versa
I would like to pass a signed int to gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n)
. 我想将一个有符号的int传递给
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. 我要传递的带符号int大于或等于零。 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. 该函数将返回一个介于
0
和n
之间的数字,因此,如果我将其传递为正号int,它将返回一个在正负int范围内的值。 I then want to store the return value in a signed int. 然后,我想将返回值存储在一个有符号的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.
我在64位Linux机器上使用64位编译器。
Update Sorry, folks. 更新抱歉,伙计们。 Please ignore.
请忽略。 The problem with my code was actually elsewhere.
我的代码的问题实际上在其他地方。 I misinterpreted the output of
gdb
. 我误解了
gdb
的输出。
Start with: 从...开始:
int input = something;
int result = gsl_rng_uniform_int(r, input);
Likely the compiler will warn about an unsafe narrowing conversion, so change to: 编译器可能会警告不安全的缩小转换,因此请更改为:
// 0 <= return value < input, so conversion is safe
int result = (int) gsl_rng_uniform_int(r, input);
Or for safety: 或出于安全考虑:
if (input <= 0) { panic(); }
unsigned long rawresult = gsl_rng_uniform_int(r, input);
if (rawresult > INT_MAX) { panic(); }
int result = (int) rawresult;
Those lines could be wrapped in a helper function: 这些行可以包装在辅助函数中:
int gsl_rng_uniform_signed(const gsl_rng *r, int input) {
if (input <= 0) { panic(); }
unsigned long rawresult = gsl_rng_uniform_int(r, input);
if (rawresult > INT_MAX) { panic(); }
return (int) rawresult;
}
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. 在任何情况下,测试您的输入通常比测试您依赖的函数的输出有用,并且如果您信任
gsl_rng_uniform_int
那么测试输入就足够了。
[Edit: wow, Google indexes SO really aggressively. [编辑:哇,Google确实对索引进行了积极地索引。 I just searched to check that
gsl_rng_uniform_signed
isn't already a function, and found myself.] 我只是搜索以确认
gsl_rng_uniform_signed
是一个函数,然后发现了我自己。]
If the function expects an unsigned long
you can pass with no problem an unsigned long
, unsigned int
, unsigned short
and unsigned char
, the standard guarantees that. 如果函数期望
unsigned long
unsigned long
unsigned int
,则可以毫无问题地传递unsigned long
, unsigned int
, unsigned short
和unsigned char
,该标准保证了这一点。
If you pass a signed
but negative int
, you will not obtain the correct results, since it will be evaluated to a very big int by the function. 如果传递一个带
signed
但为负的int
,则将不会获得正确的结果,因为该函数会将它评估为一个很大的int。
The best way is to check if it the signed int is >= 0
before passing it. 最好的方法是在传递前检查带符号的int是否
>= 0
。
I hope I understood your question correctly. 希望我能正确理解您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.