How do I inspect an integer's base-2 representation in Standard ML? [duplicate]

浪尽此生 提交于 2019-12-23 16:27:45

问题


I am trying to implement a repeated squaring algorithm in SML. I want it to be tail recursive.

The goal is to multiply all x^k where k is 2^m and 2^m is a 1 in the binary representation of n.

E.g, for x^25, calculate x^1 * x^8 * x^16 because 16 + 8 + 1 = 25

I have no idea how to represent a number by it's binary parts, or to use bitwise operations to check manually (because from what I can tell SML has no bitwise operations).

I would prefer to use the out-of-the-box SML library, so no importing other libraries.

This is a homework problem, so if you can answer without completely giving it away that would be great.

Edit: I'm using SML of New Jersey.


回答1:


Thanks to matt, I found the solution.

Using the Word type from the SML basis library, I used:

Word.andb(Word.fromInt(x), Word.fromInt(y)) > Word.fromInt(0)



来源:https://stackoverflow.com/questions/35740771/how-do-i-inspect-an-integers-base-2-representation-in-standard-ml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!