as3 writing bits to ByteArray object using writeByte method - actionscript-3

I have a string of bits(binary number) and I want to write it to a ByteArray(or maybe later in a file) is it correct to do it this way or should I first convert the binary string to hex ?
var bits:String="11001110";//8 bits a byte
var CompressedBytes = new ByteArray();
CompressedBytes.writeByte((int)(bits));
and if so please provide an example.

Your code is almost correct. Use the global parseInt(...) function that reads a given String and converts it into a Number. There's an optional second argument that allows you to specify a base of the number you are willing to parse. The most common values are 2 (for binary notation), 8 (for octal numbers), 10 (for decimal numbers, which is default) or 16 (for hexadecimal notation).
var bits:String = "11001110"; //8 bits a byte
var aByte:int = parseInt(bits, 2);
var CompressedBytes = new ByteArray;
CompressedBytes.writeByte(aByte);
P.S. You can convert a Number (also int and uint) to a String notation with a given base via toString(...) method.

Related

What is the use in having the valueOf() function?

Why is the valueOf() function present in everything in AS3? I can't think of an instance when this isn't redundant. In terms of getting a value, x and x.valueOf() are completely the same to me (except that one probably takes more CPU cycles). Furthermore even though they may not be the same in terms of setting something, x.valueOf() = y (if even legal) is just completely pointless.
I am confident though that this is here for a reason that I'm just not seeing. What is it? I did try Googling for a minute. Thanks!
As you say, its completely redundant.
The valueOf method is simply included so that ActionScript 3 complies with the ECMA language specification (obviously there are other requirements to be an ECMA language - i believe toString is another example).
Returns the primitive value of the specified object. If this object does not have a
primitive value, the object itself is returned.
Source: Adobe AS3 Reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Object.html#valueOf()
Edit:
A primitive value can be a Number, int, bool, etc... They are just the value. An object can have properties, methods, etc.
Biggest difference, in my opinion though:
primitive2 = primitive1;
In this example, primitive 2 contains a copy of the data in primitive 1.
obj2 = obj1;
In this one, however, ob2 points to the same object as obj1. Modify either obj1 or obj2 and they both reflect the change, since they are references.
In short, valueOf is used when you want to see the primitive representation of an object (if one exists) rather than the object itself.
Here is a clear example between
Value Vs. ValueOf:
Value = Thu Jan 2 13:46:51 GMT-0800 2014 (value is date formatted)
ValueOf = 1388699211000 (valueOf is in Raw epoch)
valueOf isn't useless. It allows an Object to provide a value for an expression that expects a primitive type. It's available in AS3 as well as JavaScript.
If someone wrote a function that takes an int, you could pass it your object (more precisely, it passes the result of your object's valueOf() function).
The usefulness is tempered by 1) the fact that the Object isn't passed, so it's only an Object in the outermost scope, and 2) the fact that it's a read-only operation, no assignment can be made.
Here're a couple concrete examples off the top of my head:
Example 1: A Counter class that automatically increments its value every time it's read:
class Counter
{
private var _cnt:int = 0;
public function Counter() { }
public function valueOf():int
{
return _cnt++;
}
public function toString():String { return ""+valueOf(); }
}
Usage:
var c:* = new Counter();
trace(c); // 0
trace(c); // 1
trace(2*c+c); // 2*2+3 = 7
trace(c); // 4
Notes:
I added the toString() pass-through, since functions that take String prefer toString over valueOf.
You must type c as * and not Counter, otherwise you'll get a compiler error about implicit coercion of Counter to Number.
Example 2: A (read only) pointer type
Let's say you have an array of ints, and you want to have a reference (aka pointer) to an element in the array. ECMA scripts don't have pointers, but you can emulate one with valueOf():
class ArrayIntPointer
{
private var arr:Array;
private var idx:int;
public function ArrayIntPointer(arr:Array,
idx:int)
{
this.arr = arr;
this.idx = idx;
}
public function valueOf():int
{
return arr[idx];
}
public function toString():String { return ""+valueOf(); }
}
Usage:
var arr:Array = [1, 2, 3, 4, 5];
var int_ptr:* = new ArrayIntPointer(arr, 2);
// int_ptr is a pointer to the third item in the array and
// can be used in place of an int thanks to valueOf()
trace(int_ptr); // 3
var val:int = 2*int_ptr+1;
trace(val); // 7
// but it's still an object with references, so I
// can change the underlying Array, nand now my
// object's primitive (aka, non-Object types) value
// is 50, and it still can be used in place of an int.
arr[2] = 50;
trace(int_ptr); // 50
// you can assign int_ptr, but sadly, this doesn't
// affect the array.
That's pretty slick. It'd be really slick if you could assign the pointer and affect the array, but unfortunately that's not possible, as it assigns the int_ptr variable instead. That's why I call it a read-only pointer.

How to read UTF-8 string from Socket in ActionScript 3

UTF-8 has varying amount of bytes per character. How can I understand how much bytes I can read by flash.net.Socket.readUTFBytes(length:uint):String?
There is a property available in your Socket object that will contain the information needed:
mySocket.addEventListener(ProgressEvent.SOCKET_DATA, _onSocketDataHandler);
private function _onSocketDataHandler(e:ProgressEvent):void
{
var str:String = mySocket.readUTFBytes(mySocket.bytesAvailable);
trace(str);
}

AS3 Cast Vector to Array

var leaderboardRowVOs:Vector.<LeaderboardRowVO> = new Vector.<LeaderboardRowVO>();
goes to another part of the system as an Object, and I'm trying to cast it back to actual type
notification.getBody() as Vector.<LeaderboardRowVO> //throwing error
There are two ways of type casting in AS3:
// Casting
// 1: returns null if types are not compatible,
// returns reference otherwise
notification.getBody() as Vector.<LeaderboardRowVO>
// Converting
// 2: throws exception if types are not compatible,
// returns reference otherwise
Vector.<LeaderboardRowVO>(notification.getBody())
Case 1 does not throw error, if you have such a behaviour, there must be an error in notification.getBody() method.
EDIT: #divillysausages made a clever comment about case 2 actually creating an object of another type. This is not the case here. This is what mostly happens for native types with one exception: the Array class. Some of the native classes have top level converting functions. Refer to adobe livedocs for the complete list of them. A Vector can be instantiated this way by passing an Array of appropriate types to the Vector() function.
Something else must happen to the Vector within your class because it's valid to cast a vector to Object and then back to Vector. This simple test shows it:
var v:Vector.<int> = new Vector.<int>();
v.push(1);
v.push(2);
var o:Object = v as Object;
var v2:Vector.<int> = o as Vector.<int>;
trace(v2[0]); // Output "1"
trace(v2[1]); // Output "2"
So your problem must be somewhere else.

Actionscript 3.0 String With Format?

How can i format a string with supplied variables in AS3?
//vars
var myNumber:Number = 12;
var myString:String = "Months";
var myObject:MovieClip = year;
//string
myString.txt = "One (?) consists of (?) consecutive (?)", string(myObject), string(myNumber), myString;
so in the string above, i would like myString to display "One year consists of 12 consecutive Months", but i'm new to AS3 and do not know how to properly format a string.
i'm sure that i'll have to cast the number variable into a string, string(myNumber), but i don't know if casting a movie clip variable to a string, string(myMovieClip), will return the name of the movie clip or produce an error. i'm willing to bet on the later.
The answers to this similar question suggest using the Formatter class or StringUtil.substitute().
The latter looks the simplest; in your case you would use it like this:
var str:String = "One {0} consists of {1} consecutive {2}";
var newString:String = StringUtil.substitute(str, myObject, myNumber, myString);
substitute() should automatically cast its arguments to String, but I'm not sure if, as in your code, you can cast a MovieClip (myObject) as a String.
Another good option, especially if you've used printf in other programming languages, is this third-party printf-as3 function.
Casting objects to strings
The method toString() is defined on the Object class. So all objects have this method defined for them. Calling myObject.toString() will therefore usually give you what you're looking for. Certain objects define additional methods, such as date.getHours(), which return string descriptions of the object in a different format from that supplied by getString().
For native types such as int, you can cast using String(myInt).
Concatenating strings together
You can then add together the different parts of a string as follows:
var myString:String = "There are " + String(24) + " hours in a day."
Hope that helps,
Dave
The shorter way I'd do it is something like:
var finalString:String = "One " + myObject + " consists of " + myNumber + " " + myString;
A single or double quote initiates a string literal. If you use the + symbol to append something to a string literal it's going to automatically call toString() on that object.
myObject will return [Object MovieClip], though. What you want to do is create a custom class that extends MovieClip and then override the toString() protected method to return whatever string you want it to spit out.
Hope that helps!

How to define enum in as3?

Is there a way to define an enum in AS3 in a way we do it in other languages? I can define constants with defined values like that:
private const CONST_1:int = 0;
private const CONST_2:int = 1;
private const CONST_3:int = 2;
and so on. If I want to insert some other constant between 3 these I need to move all values like that:
private const CONST_1:int = 0;
private const CONST_2:int = 1;
private const CONST_2A:int = 2;
private const CONST_3:int = 3;
while in other language I would end up with only adding a new member to enum closure like that:
enum {
CONST_1 = 0,
CONST_2,
CONST_2A,
CONST_3
} MyConstEnum;
Does AS3 has something similar?
Thanks
No AS3 doesn't have enum, you have to code them yourself. You can simulate them for example by a class if you want safer type checking.
public static var NUM_ENUM_VALUES:int = 0;
public static const EV_MONDAY:int = NUM_ENUM_VALUES++;
public static const EV_TUESDAY:int = NUM_ENUM_VALUES++;
public static const EV_WEDNESDAY:int = NUM_ENUM_VALUES++;
public static const EV_THURSDAY:int = NUM_ENUM_VALUES++;
You can take a look at the variety of variable types supported by the ActionScript Virtual Machine. Variable types are annotated by traits, the variety of which can be found in the specification, table 4.8.1:
4.8.1 Summary of trait types
The following table summarizes the trait types.
Type Value
Trait_Slot 0
Trait_Method 1
Trait_Getter 2
Trait_Setter 3
Trait_Class 4
Trait_Function 5
Trait_Const 6
There is no Trait_Enum and note that under Trait_Const description, only constants from the constant pool are allowed, so that would be:
signed integers
unsigned integers
doubles
strings
type names and vector types
Enums could be made of signed or unsigned integers, for example, but the virtual machine would not perform any type-safety checking of the operations which used those types. (E.g., the getlocal or coerce opcodes used would be getlocal_i and coerce_i, respectively.)
The ABC format doesn't have any built-in provision for enum types that I know of.
Using an object type for each enum value could work, especially if the compiler emits coerce instructions for that type prior to uses of getlocal and otherwise doesn't use the object other than in istype and astype variants. For example, calling setproperty or getproperty on the object would be slower than using an integer -- especially if that property is bound to a getter or setter method.
There are replacement styles which have been linked in other answers. To evaluate the runtime performance impact of these styles, you can uses swfdump -D from the swftoools open-source Flash tools collection.