1

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

Reynald
  • 11
  • 1
  • Since your are asking for an integer there is no platforms difference, MSB and LSB is always the same – mathk Jul 05 '10 at 21:39

5 Answers5

2

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"

Friedrich
  • 5,916
  • 25
  • 45
0

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)

Stephan Eggermont
  • 15,847
  • 1
  • 38
  • 65
0

Try digitAt: and digitAt:put::

(333 digitAt: 1) hex '4D'
robert
  • 1
0

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.

blabla999
  • 3,130
  • 22
  • 24
0

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.