c - 如何在 Linux 内核中划分两个 64 位数字?

标签 c linux 64-bit

将除法四舍五入进行演示的一些代码(C 语法):

#define SINT64 long long int
#define SINT32 long int

SINT64 divRound(SINT64 dividend, SINT64 divisor)
{
  SINT32 quotient1 = dividend / divisor;

  SINT32 modResult = dividend % divisor;
  SINT32 multResult = modResult * 2;
  SINT32 quotient2 = multResult / divisor;

  SINT64 result = quotient1 + quotient2;

  return ( result );
}

现在,如果这是用户空间,我们可能甚至不会注意到我们的编译器正在为这些运算符生成代码(例如,用于除法的 divdi3())。我们很可能在不知情的情况下链接了 libgcc。问题是内核空间不同(例如,没有 libgcc)。怎么办?

在 Google 上爬了一会儿,注意到几乎每个人都在处理未签名的变体:

#define UINT64 long long int
#define UINT32 long int

UINT64 divRound(UINT64 dividend, UINT64 divisor)
{
  UINT32 quotient1 = dividend / divisor;

  UINT32 modResult = dividend % divisor;
  UINT32 multResult = modResult * 2;
  UINT32 quotient2 = multResult / divisor;

  UINT64 result = quotient1 + quotient2;

  return ( result );
}

我知道如何解决这个问题:用 asm/中的 do_div() 覆盖 udivdi3()umoddi3() div64.h。做对了吗?错误的。 Signed 与 unsigned 不同,sdivdi3() 不是简单地调用 udivdi3(),它们是独立的函数是有原因的。

这个问题你解决了吗?你知道有图书馆可以帮助我做到这一点吗?我真的被困住了,所以无论您在这里看到我现在还没有看到的什么,都会非常有帮助。

谢谢, 乍得

最佳答案

此功能在 /linux/lib/div64.c 中引入早在内核 v2.6.22。

关于c - 如何在 Linux 内核中划分两个 64 位数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463/

相关文章:

linux - 获取错误 sed : -e expression #1, 字符 5:未知命令: `0'

python - 在 64 位 Windows 7 机器上使用 Python 构建 Com 服务器

c - 尝试从 OS Dev 教程编译代码

c - 位流在C中保存为uint8_t

c - .c 文件中的内联 PPC 汇编代码出现 "Error: unsupported relocation against <register>"错误

c - 警告 C4047 : '=' : 'char' differs in levels of indirection from 'char *'

linux - bash中的-z是什么

linux - 通过 bash 脚本查找和 Xargs 复制和重命名

ios - iOS 中静态库的 64 位支持

assembly - x64 - 为什么仍然使用 'call' ?