ActionScript 3: ByteArray to binary String - string

I've been asked to implement and MD5 hasher ActionScript-3 and as I was in the middle of debugging how I formatted my input I came across a problem. When I try and output the ByteArray as a binary string using .toString(2), the toString(2) method will perform some short cuts that alter how the binary should look.
For Example
var bytes:ByteArray = new ByteArray();
bytes.endian = Endian.LITTLE_ENDIAN;
bytes.writeUTFBytes("a");
bytes.writeByte(0x0);
var t1:String = bytes[0].toString(2); // is 1100001 when it should be 01100001
var t2:String = bytes[1].toString(2); // is 0 when it should be 00000000
so I guess my question is, might there a way to output a binary String from a ByteArray that will always shows each byte as a 8 bit block?

All you need is to pad the output of toString(2) with zeros on the left to make its length equal to 8. Use this function for padding
function padString(str:String, len:int, char:String, padLeft:Boolean = true):String{
var padLength:int = len - str.length;
var str_padding:String = "";
if(padLength > 0 && char.length == 1)
for(var i:int = 0; i < padLength; i++)
str_padding += char;
return (padLeft ? str_padding : "") + str + (!padLeft ? str_padding: "");
}
With this function the code looks like this and gives the correct output
var bytes:ByteArray = new ByteArray();
bytes.endian = Endian.LITTLE_ENDIAN;
bytes.writeUTFBytes("a");
bytes.writeByte(0x0);
var t1:String = padString(bytes[0].toString(2), 8, "0"); // is now 01100001
var t2:String = padString(bytes[1].toString(2), 8, "0"); // is now 00000000
Update
If you want to get a string representation of complete byteArray you can use a function which iterates on the byteArray. I have wrote the following function and it seems to work correctly. Give it a try
// String Padding function
function padString(str:String, len:int, char:String, padLeft:Boolean = true):String{
// get no of padding characters needed
var padLength:int = len - str.length;
// padding string
var str_padding:String = "";
// loop from 0 to no of padding characters needed
// Note: this loop will not run if padLength is less than 1
// as i < padLength will be false from begining
for(var i:int = 0; i < padLength; i++)
str_padding += char;
// return string with padding attached either to left or right depending on the padLeft Boolean
return (padLeft ? str_padding : "") + str + (!padLeft ? str_padding: "");
}
// Return a Binary String Representation of a byte Array
function byteArrayToBinaryString(bArray:ByteArray):String{
// binary string to return
var str:String = "";
// store length so that it is not recomputed on every loop
var aLen = bArray.length;
// loop over all available bytes and concatenate the padded string to return string
for(var i:int = 0; i < aLen; i++)
str += padString(bArray[i].toString(2), 8, "0");
// return binary string
return str;
}
Now you can simply use the byteArrayToBinaryString() function like this:
// init byte array and set Endianness
var bytes:ByteArray = new ByteArray();
bytes.endian = Endian.LITTLE_ENDIAN;
// write some data to byte array
bytes.writeUTFBytes("a");
bytes.writeByte(0x0);
// convert to binaryString
var byteStr:String = byteArrayToBinaryString(bytes); // returns 0110000100000000

Here is a function extended on the Hurlant library to handle hashing byteArray.
This class has a learning curve but once you get it you will love it.
As far as your ByteArray issue with toString. I know the toString method is not accurate For this very reason.
You might want to look into byteArray.readMultiByte that will give you the 01 you are looking for. Although I can't seem top get it to work on my sample code either lol
I just always get a and empty string.
var bytes:ByteArray = new ByteArray();
bytes.endian = Endian.LITTLE_ENDIAN;
bytes.writeUTFBytes("a");
bytes.writeByte(0x0);
bytes.position = 0
var t1:String = bytes.readMultiByte(1,'us-ascii'); // is 1100001 when it should be 01100001
trace(t1)
var t2:String = bytes.readMultiByte(1,'iso-8859-01'); // is 0 when it should be 00000000
trace(t2)

Related

How to convert string and integer to binary in nodejs?

I have the following problems. I have an integer and a string. Both of them need to be converted into binary format. For the integer I found a solution that, as far as I can tell, works. The string on the other hand, I don't have a solid understanding of it.
String(16), as far as I understand, means something like Array<UInt8> and has a fixed length of 16. Am I correct? If so, is there a better way to converting them by hand built in in NodeJS?
const myNumber = 2
const myString = 'MyString'
const myNumberInBinary = toUInt16(myNumber) // eg. 0000000000000101
const myStringinBinary = toString16(myString) // I honestly don't know
function toUInt16(number) {
let binaryString = Number(number).toString(2)
while (binaryString.length < 16) {
binaryString = '0' + binaryString
}
return binaryString
}
// TODO: implement
function toString16(string) {
...
return binaryString
}
best regards
EDIT:
Thanks for all the comments and the answer. They helped me understand this process better. The solution I ended up with is this one:
const bitString = "00000101"
const buffer = new Buffer.alloc(bitString.length / 8)
for (let i = 0; i < bitString.length; i++) {
const value = bitString.substring(i * 8, (i * 8) + 8)
buffer[i] = Number(value)
}
fs.writeFileSync('my_file', buffer, 'binary')
Thanks again!
You should loop through the string and do this on each character:
let result = ""
for (let i = 0; i < myString.length; i++) {
result += myString[i].charCodeAt(0).toString(2) + " ";
}

How to make a string shift backward each letter

I am finishing some functions in a flutter project.
void code_shift_backward() {
var input_string = controller.text;
List<String> output_list = [];
var input_runes = input_string.runes.toList();
for (var rune in input_runes) {
var mutatedRune = rune--;
output_list.add(String.fromCharCode(mutatedRune));
}
var output_string = output_list.join("");
setState(() {
text_in_tree = output_string;
});
}
I give it the word wiggle and I expect vhffkd but it keeps giving wiggle
You have to change:
var mutatedRune = rune--;
to:
var mutatedRune = --rune;
Explanation:
rune-- assigns the value of rune to mutatedRune first, then reduces the value by one. It means mutatedRune and rune has the same value.
--rune reduces the value first, then assigns.
Read about Dart arithmetic operators for more details.
You can fix this by moving the -- to the front of rune.. This happens because putting the -- after the variable only updates the variable after that line.
void code_shift_backward() {
var input_string = controller.text;
List<String> output_list = [];
var input_runes = input_string.runes.toList();
for (var rune in input_runes) {
var mutatedRune = --rune;
output_list.add(String.fromCharCode(mutatedRune));
}
var output_string = output_list.join("");
setState(() {
text_in_tree = output_string;
});
}
For size, maybe:
String shiftBack(String input) =>
String.fromCharCodes([for (var c in input.runes) c - 1]);

How to manipulate a string representing a raw number (e.g. 130000.1293) into a formatted string (e.g. 130,000.13)?

In apps script I want to obtain formatted 'number' strings. The input is an unformatted number. With an earlier answer posted by #slandau, I thought I had found a solution by modifying his code (see code snippet). It works in codepen, but not when I am using apps script.
1. Does anyone know what went wrong here?
2. I noticed this code works except when entering a number ending in .0, in that case the return value is also .0 but should be .00. I would like some help fixing that too.
Thanks!
I have tried to look for type coercion issues, but wasn't able to get it down. I am fairly new to coding.
function commaFormatted(amount)
{
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2);
var preD = a[1]/(Math.pow(10,a[1].length-2));
var d = Math.round(preD);
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
console.log(commaFormatted('100000.3532'))
The expected result would be 100,000.35.
I am getting this in the IDE of codepen, but in GAS IDE is stops at the .split() method => not a function. When converting var a to a string = I am not getting ["100000", "3532"] when logging var a. Instead I am getting 100000 and was expecting 3532.
Based on this answer, your function can be rewritten to
function commaFormatted(amount)
{
var inputAmount;
if (typeof(amount) == 'string') {
inputAmount = amount;
} else if (typeof(amount) == 'float') {
inputAmount = amount.toString();
}
//--- we expect the input amount is a String
// to make is easier, round the decimal part first
var roundedAmount = parseFloat(amount).toFixed(2);
//--- now split it and add the commas
var parts = roundedAmount.split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
console.log(commaFormatted(100000.3532));
console.log(commaFormatted('1234567.3532'));

can only write to buffer byte by byte, buf.write() says argument must be string... but it is Node

I'm trying to use the Buffer module in Node to convert between encoding types. It works for my purposes when I write the string to the buffer byte by byte, but buf.write() says argument must be a string, even though I am passing it a string.
This works:
var buf = new Buffer(this.length)
for(var i = 0; i < this.length; i++){
buf[i] = this.charCodeAt(i)
}
return buf.toString('base64')
This doesn't:
// Inside String.prototype.base64()
var buf = new Buffer(this.length)
buf.write(this, 0, this.length, 'base64')
You are passing string OBJECT to the buffer, not a simple string. So to solve it try:
var buf = new Buffer(this.length)
buf.write(this.toString(), 0, this.length, 'base64')

AS3 String splitting keeping tags

I have variable strings that can contain tags, e.g.:
"<b>Water</b>=H<sub>2</sub>O"
What i want is an array that should look like:
Array[0] <b>Water</b>
Array[1] =H
Array[2] <sub>2</sub>
Array[3] O
How can i do this?
Thanks!
Give this a go, it uses a common regex to find html tags to get it separated and then indexOf and substring to assemble it back together.
function splitWithTags(str:String):Array {
var tags:Array = str.match(/(<(.|\n)*?>)/g);
var c:int = tags.length;
if(c%2 != 0) c--; // if it's odd, decrement to make even so loop works, last tag will be ignored.
if(c<2) return [str]; // not enough tags so return full string
var out:Array = [];
var end:int = 0;
var pos1:int, pos2:int;
for(var i:int = 0; i<c; i+=2) {
// find position of 2 tags.
pos1 = str.indexOf(tags[i]);
pos2 = str.indexOf(tags[i+1]);
if(pos1 >= end+1) { // there's some stuff not between tags to add
out.push(str.substring(end, pos1));
}
end = pos2+tags[i+1].length
out.push(str.substring(pos1, end));
}
if(end < str.length) { // there is substr at end
out.push(str.substring(end, str.length));
}
return out;
}

Resources