博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Compute modulus division by a power-of-2-number
阅读量:4151 次
发布时间:2019-05-25

本文共 644 字,大约阅读时间需要 2 分钟。

reference: 

Problem Definition:

Compute n modulo d without division(/) and modulo(%) operators, where d is a power of 2 number.

Solution:

Let ith bit from right is set in d. For getting n modulus d, we just need to return 0 to i-1 (from right) bits of n as they are and other bits as 0.

For example if n = 6 (00..110) and d = 4(00..100). Last set bit in d is at position 3 (from right side). So we need to return last two bits of n as they are and other bits as 0, i.e., 00..010.

Code:

/* This function will return n % d.   d must be one of: 1, 2, 4, 8, 16, 32, … */unsigned int getModulo(unsigned int n, unsigned int d){  return ( n & (d-1) );}

转载地址:http://aexti.baihongyu.com/

你可能感兴趣的文章
常用js收集
查看>>
如何防止sql注入
查看>>
springmvc传值
查看>>
在Eclipse中查看Android源码
查看>>
Android使用webservice客户端实例
查看>>
[转]C语言printf
查看>>
C 语言学习 --设置文本框内容及进制转换
查看>>
C 语言 学习---判断文本框取得的数是否是整数
查看>>
C 语言 学习---ComboBox相关、简单计算器
查看>>
C 语言 学习---ComboBox相关、简易“假”管理系统
查看>>
C 语言 学习---回调、时间定时更新程序
查看>>
C 语言 学习---复选框及列表框的使用
查看>>
第十一章 - 直接内存
查看>>
JDBC核心技术 - 上篇
查看>>
一篇搞懂Java反射机制
查看>>
Single Number II --出现一次的数(重)
查看>>
Palindrome Partitioning --回文切割 深搜(重重)
查看>>
对话周鸿袆:从程序员创业谈起
查看>>
Mysql中下划线问题
查看>>
Xcode 11 报错,提示libstdc++.6 缺失,解决方案
查看>>