Apple Game Frameworks and Technologies: Wrote binary, meant decimal (p 85)

At the bottom of page 85 is this info box:

By default, integer literals are expressed in decimal using the numbers 0 through 9. However, you can modify this default behavior and use binary literals instead, which might make it easier. With binary literals, you use the prefix 0b. Unlike integer literals, binary literals use only 0 and 1. So, in this example, 0b100 equals the number four. Essentially, this is shorthand for 000000100. If you choose to use binary literals, you’ll need to work in squares: 1, 2, 4, 8, 16, and so on.

The last sentence says If you choose to use binary literals, you’ll need to work in squares: 1, 2, 4, 8, 16, and so on. I think that’s a typo and was meant to read: “If you choose to use decimal literals…”

2 Likes

Hello, David.

An integer literal represents some arbitrary value. You can express this value as a decimal, binary, octal, or hexadecimal constant. Binary literals begin with 0b, octal literals begin with 0o, and hexadecimal literals begin with 0x. Decimal literals have no prefix—they are what they are.

In this case, the physics category is a single 32-bit integer that acts as a mask, and each bit represents a single category, which is why you’re limited to 32 categories per scene. With masking, using powers of two makes things easier—especially when using binary literals.

Now, having said that, what you pointed out wasn’t actually a typo, but the information was certainly misleading. What it should have read–and now does read–is as follows:

When setting your categories, it’s best to do so using powers of two: 1, 2, 4, 8, 16, and so on.

You’ll see this new explanation in the next update.

Also, later in the book, I explain how to create and use a Hashable OptionSet to set up and retrieve the physics category—something that is also mentioned in that same aside. Enums are great, and for simpler games, preferred. However, as your game grows in complexity, Hashable OptionSets provide a bit more flexibility. You’ll see this solution in use when you get to Val’s Revenge.

Thanks again for pointing this out. Have a great day.

2 Likes

When setting your categories, it’s best to do so using powers of two: 1, 2, 4, 8, 16, and so on.

Yes I agree this will read better. Regardless of which system we use, the mask values ought to be 1, 2, 4, 8, 16 etc… In decimal we will actually use the literals 1, 2, 4, 8, 16.

In binary we will be representing those values using only 0, 1, and the letter b (e.g. 0b100 for 4). It was confusing previously when it said that if you choose to use binary you’ll need to work with 1, 2, 4. You were referring to the mask values, I thought you were referring to the literals. The new text makes it clear you are referring to the category values.

4 Likes