Bit and Byte classes in ActionScript

One of the features of ActionScript (good or bad depending on your point of view) is that it only has a few built in primitive types namely int, unit, Number and Boolean. Unlike other languages there's no long or byte type. I'm current working on a project that involves a lot of mucking about with bits and bytes and I thought I'd share the code.

The ActionScript classes below are not going to be faster or take up less memory than using a int or other primitive type but they will make you code a lot easer to read and maintainable and pick up a more errors at compile time.

Bit class

The Byte class will restrict values of 0 and 1 and provides convenience functions to convert to other types int, String or Boolean.

The class uses a neat trick with a static code block to ensure you can't call the constructor but need to assign newly created variables to the static constants Bit.ONE or Bit.ZERO. You can use the same technique to make enum classes.

view plain print about
1package com.classsoftware.binary
2{
3    /**
4     * Repersents a single bit. Use the static constants when creating bits rather than creating them via the constructor.
5     * Like so:
6     * <listing>
7     *     var bit:Bit = Bit.ONE;
8     * </listing>
9     *
10     * @author justinmclean
11     */

12    public class Bit
13    {
14        
15        /**
16         * Same as ZERO. Bit with a value of '0'.
17         */
            
18        public static const FALSE:Bit = Bit.ZERO;
19        
20        /**
21         * Bit with a value of '1'.
22         */

23        public static const ONE:Bit = new Bit(true);
24        
25        /**
26         * Same as ONE. Bit with a value of '1'.
27         */
        
28        public static const TRUE:Bit = Bit.ONE;
29        
30        /**
31         * Bit with a value of '0'.
32         */

33        public static const ZERO:Bit = new Bit(false);
34
35        private static var _created:Boolean = false;
36
37        /*
38         * Static code block this is executed before the constructor but after any statics properties have been created.
39         * We can use this to make a constructor that throws an error at runtime if called.
40         */

41        {
42            _created = true;
43        }
44        
45        /**
46         * Creates a bit. Use static constants ONE, ZERO, TRUE or FALSE when creating bits instead of this constructor.
47         * Uses a a staic code block and a boolean check to emulate a private constructor. In Acrionscript all constructors are public.
48         * @param value value (true or false) to set bit to.
49         * @default false
50         */

51        public function Bit(value:Boolean = false)
52        {
53            init(value);
54        }
55        
56        // check if instance has been created and if so throw an error otherwise set the value to 0 or 1
57
        private function init(value:Boolean):void {
58            if (_created) {
59                throw new Error('Plese use static constants Bit.ZERO, Bit.ONE, Bit.TRUE or Bit.FALSE');
60            }
61            _value = value;
62        }
63        
64        private var _value:Boolean = false; // TODO check if boolean or int is faster
65

66        /**
67         * Converts a Bit to a Boolean.
68         * @return true or false depending on value of bit
69         */

70        public function toBoolean():Boolean {
71            return _value;
72        }
73        
74        /**
75         * Converts a Bit to an int.
76         * @return 0 or 1 depending on value of bit
77         */

78        public function toInt():int {
79            return int(_value);
80        }
81        
82        /**
83         * Converts a Bit to a String.
84         * @return "0" or "1" depending on value of bit
85         */

86        public function toString():String {
87            return int(_value).toString();
88        }
89    }
90}

Byte

The Byte class will restrict values between 0 and 0xFF and provides convenience functions to set and clear bits, test if a bit and convert to other types int or String.

view plain print about
1package com.classsoftware.binary {
2    /**
3     * Implements a Byte type with values in the range of 0 to 0xFF.
4     * <listing>
5     *     var byte:Byte = new Byte(0xFF);
6     * </listing>
7     * @author justinmclean
8     */

9    public class Byte {
10
11        /**
12         * Creates a Byte and optionally sets it value.
13         * @param value Value to set Byte to (0 - 0xFF).
14         */

15        public function Byte(value:int = 0) {
16            _value = value & 0xFF;
17        }
18
19        private var _value:int = 0;
20        
21        /**
22         * Clears a bit in a Byte.
23         * @param bit The bit (0-7) to clear.
24         */

25        public function clearBit(bit:int):void {
26            _value &= ~(1 << bit);            
27        }
28        
29        /**
30         * Decrements the value of a byte by one.
31         * @return The new value.
32         */

33        public function dec():Byte {
34            _value--;
35            return this;
36        }
37
38        /**
39         * Returns a bit from a Byte,
40         * @param bit The bit (0-7) to return.
41         * @return Bit.ONE if bit is set and Bit.ZERO is bit is not set.
42         */

43        public function getBit(bit:int):Bit {
44            var result:Bit;
45            
46            if (_value & (1 << bit)) {
47                result = Bit.ONE;
48            } else {
49                result = Bit.ZERO;
50            }
51            
52            return result;
53        }
54        
55        /**
56         * Increments the value of a byte by one.
57         * @return The new value.
58         */

59        public function inc():Byte {
60            _value++;
61            return this;
62        }
63
64        /**
65         * Returns id a bit (0-7) is set in a Byte.
66         * @param bit Bit (0-7) to test if test
67         * @return True is bit is set, false if bit is not set.
68         */

69        public function isBitSet(bit:int):Boolean {
70            var result:Boolean;
71            
72            if (_value & (1 << bit)) {
73                result = true;
74            } else {
75                result = false;
76            }
77            
78            return result;
79        }
80
81        /**
82         * Sets a bit (0-7) in a Byte.
83         * @param bit Bit to set.
84         */

85        public function setBit(bit:int):void {
86            _value |= (1 << bit);
87        }
88
89        /**
90         * Converts a twos compliment number to a decimal number.
91         * @param bits No of bits in the number.
92         * @default bits 8
93         * @return A positve or negative number.
94         */

95        public function toDec(bits:int = 8):int {
96            var neg:int = 1 << (bits - 1);
97            var dec:int = 0;
98
99            if (_value >= neg) {
100                dec = ~_value & (neg - 1);
101                dec = -(dec + 1);
102            } else {
103                dec = _value;
104            }
105
106            return dec;
107        }
108
109        /**
110         * Converts a Byte to a String.
111         * @return A 2 digit hexadecimal number.
112         */

113        public function toString():String {
114            var textmem:String = _value.toString(16);
115            
116            if (value < 0x10) {
117                textmem = '0' + textmem;
118            }
119            
120            return textmem;
121        }
122
123        /**
124         * Return the value of a Byte.
125         * @return Value of the Byte.
126         */

127        public function get value():int {
128            return _value;
129        }
130
131        /**
132         * Sets the value of a Byte.
133         * @param value Value to set the Byte to.
134         */

135        public function set value(value:int):void {
136            _value = value & 0xFF;
137        }
138    }

Related Blog Entries

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
I have refactored this classes and made quite a few improvements. The code is also now open source (under the MIT licence) and can be found at githug here:
http://github.com/justinmclean/ActionScript-Binary...
# Posted By Justin Mclean | 10/24/10 10:09 PM