从unsigned long int转换为signed int,反之亦然 [英] Converting from unsigned long int to signed int and vice versa

查看:404
本文介绍了从unsigned long int转换为signed int,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将signed int传递给 gsl_rng_uniform_int(const gsl_rng * r,unsigned long int n)。我传递的signed int大于或等于零。该函数将在 0 n 之间返回一个数字,所以如果我传递一个正的signed int,它将返回在signed int范围内的东西。然后我想将返回值存储在signed int中。用明显的预期行为来做到这一点最简洁的方法是什么?我在64位Linux机器上使用64位编译器。

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.

更新
抱歉,伙计们。请忽略。我的代码问题其实在其他地方。我误解了 gdb 的输出。

推荐答案

开头:

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);

或者为了安全:

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;
}

在任何情况下,测试输入通常比测试函数输出更有用你依赖,如果你信任 gsl_rng_uniform_int 那么测试输入就足够了。

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.

这篇关于从unsigned long int转换为signed int,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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