/*
 * Copyright 2006 by Cisco Systems, Inc.,
 * 170 West Tasman Drive, San Jose, California, 95134, U.S.A.
 * All rights reserved.
 * 
 * This software is the confidential and proprietary information of Cisco
 * Systems, Inc. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with the
 * terms of the license agreement you entered into with Cisco.
 *
 * Purpose: binary & string utility functions.
 * Author: Robert Mars (rmars@cisco.com)
 * Date: 10/25/06
 */

/**
 * Converts binary string to decimal.
 *
 * Each set of 8 bits is converted into a byte.
 *
 * @param s binary string of '0's and '1's
 * @return byte array of decimal equivalent
 */
function asciiBinary2bytes(s) {
    var asciiBinaryBytes = s.getBytes();

    for (var i=0; i<asciiBinaryBytes.length; i++) {
        asciiBinaryBytes[i] -= 48; // convert ASCII ('0'==48) to decimal
    }

    var byteArray = bits2bytes(asciiBinaryBytes);

    return byteArray;
}


/**
 * Pads a string with specified character to the specified length.
 *
 * @param s string to be padded
 * @param c character to pad with
 * @param totalLen total length string is to have
 * @return padded string
 */
function padString(s, c, totalLen) {
    for (var i=s.length; i<totalLen; i++) {
        s += c;
    }

    return s;
}
        

/**
 * Converts bytes to hexadecimal form.
 *
 * @param byteArray array of bytes to be converted to hex
 * @return hexadecimal form of byteArray
 */
function bytes2hex(byteArray) {
    var encryptedChars = "";

    for (var k = 0; k < byteArray.length; k++) {
        var i1 = (byteArray[k] & 0xF0) >> 4;
        var i2 = (byteArray[k] & 0x0F);
        //alert("byteArray["+k+"]="+byteArray[k]+", i1="+i1+", i2="+i2);
        var c1 = (i1 < 10 ? 48 + i1 : 55 + i1).toString(); // 48==ASCII 0
        var c2 = (i2 < 10 ? 48 + i2 : 55 + i2).toString(); // (10+55)65==ASCII A
        encryptedChars += String.fromCharCode(c1);
        encryptedChars += String.fromCharCode(c2);
    }

    return encryptedChars;
}


/**
 * Converts bit array to 0's & 1's to bytes.
 *
 * Each octet of bits is represented in a single byte.
 *
 * @param bitArray array of bits to be converted to bytes
 * @return byte array representation of bit array
 */
function bits2bytes(bitArray) {
    //alert("bitArray.length="+bitArray.length);

    var nBytes = bitArray.length / 8;

    byteArray = new Array(nBytes);

    for (var k = 0; k < nBytes; k++) {
        var mask = 0;

        for (var i = 0; i < 8; i++) {
            if ((bitArray[(k*8)+i] & 0xFF) == 1) {
                mask = mask | (0x80>>i);
            }
        }
        //alert("mask="+mask);

        byteArray[k] = mask;
    }

    return byteArray;
}
