开发者

How to get the bytes that makeup an integer?

开发者 https://www.devze.com 2023-01-05 06:14 出处:网络
In Smalltalk (or at least Squeak and Pharo), is there a portable way to get the bytes that make up 开发者_C百科an integer, starting with the most significant byte followed by the next-most, and so on,

In Smalltalk (or at least Squeak and Pharo), is there a portable way to get the bytes that make up 开发者_C百科an integer, starting with the most significant byte followed by the next-most, and so on, regardless of byte-ordering differences across platforms?


1 to: (31 highBitOfMagnitude) do: [:i | Transcript show: (31 bitAt: i)].

Or something along this lines.

Sorry I have read bits and not bytes. So you have to bundle the bits into bytes. Assuming you mean a byte = 8 bit this should be "doable"


You are aware that might be a lot of bytes? Integers can be of arbitrary size, with SmallIntegers as direct objects of 31 bit (in a 32-bit image)


Try digitAt: and digitAt:put::

(333 digitAt: 1) hex '4D'


Robert is right: digitAt:idx retrieves a byte, starting with an index of 1 (as usual) for the low-byte. digitLength gives you the number of digits.

So to enumerate use:

n digitLength downTo:1 do:[:idx | do something with (n digitAt:idx)]

I am not sure, if there is a convention on what is returned for large negative numbers, because Smalltalks tend to use sign-value representation for LargeInts but 2's complement for SmallInts. So you might have to check for this.

Caveat: to me, digitAt: is a bit of a bad name - I tend to associate it with "decimal-digit-at", which is misleading.


That depends on how your number is represented. If you just wanted to get the digits of the number you could do something like

12345 printString do: [ :c | "Your code to manipulate the digits here" ]

Share and enjoy.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号