简体   繁体   English

如何使用C将int分配给unsigned long?

[英]How to assign an int to unsigned long using C?

I am using C language. 我正在使用C语言。 There is a function named "npu_session_total". 有一个名为“ npu_session_total”的函数。 Then, I will use the return value of this func and assign it to an unsigned long variable "accelerated_count". 然后,我将使用此func的返回值,并将其分配给一个无符号的长变量“ accelerated_count”。

int npu_session_total(void)
{
    // this will return an int
    return atomic_read(&npu_session_count);
}
........
unsigned long accelerated_count = npu_session_total();

Will this cause any problems? 这会引起任何问题吗? How can I do the cast? 我该怎么做演员?

Thanks! 谢谢!

Assigning an int to a unsigned long can be done simply as OP did. 可以像OP一样简单地将int分配给unsigned long It is well defined in C. When some_int_value >= 0 it will always fit unchanged into an unsigned long . 它在C中定义良好。当some_int_value >= 0 ,它将始终保持不变,成为unsigned long

INT_MAX <= UINT_MAX <= ULONG_MAX

No cast, masking, nor math is needed - just like OP did. 就像OP一样,不需要强制转换,遮罩或数学运算。

unsigned long some_unsigned_long_object = some_int_value;

The trick is when some_int_value < 0 . 诀窍是当some_int_value < 0 The value saved will be some_int_value + ULONG_MAX + 1 . 保存的值将为some_int_value + ULONG_MAX + 1 @AnT Now is this OK for OP's code? @AnT现在可以使用OP的代码了吗? Perhaps not. 也许不是。

A safer conversion would test for negativeness first. 较安全的转换会首先测试否定性。

int session_total = npu_session_total();
if (session_total < 0) {
  Handle_Negative_Case(session_total);
}
else {
  unsigned long accelerated_count = npu_session_total();
  ...
}

@OP comments that the int value should never be negative. @OP注释int值永远不应为负。 Defensive coding would still detect negative values and handle that. 防御性编码仍将检测负值并进行处理。 Maybe a simple error message and exit. 也许是一个简单的错误消息并退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM