[Newbies] Unsigned interpretation

David T. Lewis lewis at mail.msen.com
Fri Dec 6 00:40:12 UTC 2013

On Thu, Dec 05, 2013 at 11:05:15PM +0500, Azka Niazi wrote:
> Is there a preexisting method in Squeak 2.8 or 4.1 which can interpret a binary number as an unsigned number?
> Thanks,Azka 		 	   		  

Hi Azka,

I am assuming that you are interested in treating some binary data as an
unsigned integer value, and you want to read that data and convert it into
a positive integer in Smalltalk.

The easiest way to do this is to read the binary data into a Smalltalk
ByteArray, and then convert that ByteArray into an integer value. Let's
assume that the binary data is 32 bits in length (4 bytes), which is a
common format. And let's also assume that the binary data was stored in
"little endian" format, which is the convention used by most PC computers

It just so happens that the first four bytes of a Squeak image file are an
unsigned integer value that identifies what kind of image it is (there are
various versions, so the Squeak virtual machine needs to know this in order
to load an image file). So using this as an example, here is how to read
the first four bytes of a Squeak image file and convert it into a positive
integer in Smalltalk:

  fs := FileStream readOnlyFileNamed: Smalltalk imageName. "Open the image file"
  fs binary. "Set it to binary mode so you get a ByteArray when you read from it"
  [someBytes := fs next: 4] ensure: [fs close]. "Read the first four bytes into a ByteArray"
  anUnsignedInteger := someBytes unsignedLongAt: 1 bigEndian: false. "Convert it to Integer"
  anUnsignedInteger inspect.

If you evaluate this in a workspace, you will see the integer value of
the image format number for that Squeak image file. It will be either 6504
or 6505, depending on which VM had been used to save the image file.

If you look at class ByteArray in category 'platform independent access'
you will also find a few other methods for converting binary data into
integer and floating point values.


More information about the Beginners mailing list