如何在 Linux Kernel 中划分两个 64 位数字? [英] How to divide two 64-bit numbers in Linux Kernel?

查看:19
本文介绍了如何在 Linux Kernel 中划分两个 64 位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Some code that rounds up the division to demonstrate (C-syntax):

#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).怎么办?

Now, if this were User-space we probably wouldn't even notice that our compiler is generating code for those operators (e.g. divdi3() for division). Chances are we link with libgcc without even knowing it. The problem is that Kernel-space is different (e.g. no libgcc). What to do?

在 Google 上搜索一段时间,注意几乎每个人都在处理未签名的变体:

Crawl Google for a while, notice that pretty much everyone addresses the unsigned variant:

#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(),它们是有原因的独立函数.

I know how to fix this one: Override udivdi3() and umoddi3() with do_div() from asm/div64.h. Done right? Wrong. Signed is not the same as unsigned, sdivdi3() does not simply call udivdi3(), they are separate functions for a reason.

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

Have you solved this problem? Do you know of a library that will help me do this? I'm really stuck so whatever you might see here that I just don't right now would be really helpful.

谢谢,乍得

推荐答案

此功能在 /linux/lib/div64.c 早在内核 v2.6.22.

This functionality is introduced in /linux/lib/div64.c as early as kernel v2.6.22.

这篇关于如何在 Linux Kernel 中划分两个 64 位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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