Tuesday, June 18, 2013

Performing Operations on Byte Arrays ( CSharp Solutions - C# )

When working with digital electronics, this can be easily accomplished with a few flip-flops and logic operators. To program something like this is just as easy - when one can rap their mind around it! I successfully wrote addition and subtraction methods that would perform these respective operations on raw byte arrays, many months ago. I lost the sources and had to really think how to replicate my results. Today I have not only successfully rewritten the source code but also composed them to add more than just one byte to an array of bytes.




Addition

public static byte[] Add(this byte[] A, byte[] B)
{
    List<byte> array = new List<byte>(A);
    for (int i = 0; i < B.Length; i++)

        array = _add_(array, B[i], i);

    return array.ToArray();
}
private static List<byte> _add_(List<byte> A, byte b, int idx = 0, byte rem = 0)
{
    short sample = 0;
    if (idx < A.Count)
    {
        sample = (short)((short)A[idx] + (short)b);
        A[idx] = (byte)(sample % 256);
        rem = (byte)((sample - A[idx]) % 255);
        if (rem > 0)
            return _add_(A, (byte)rem, idx + 1);
    }
    else A.Add(b);

    return A;
}


Subtraction

public static byte[] Subtract(this byte[] A, byte[] B)
{
    // find which array has a greater value for accurate
    // operation if one knows a better way to find which 
    // array is greater in value, do let me know. 
    // (MyArray.Length is not a good option here because
    // an array {255} - {100 000 000} will not yield a
    // correct answer.)
    int x = A.Length-1, y = B.Length-1;
    while (A[x] == 0 && x > -1) { x--; }
    while (B[y] == 0 && y > -1) { y--; }
    bool flag;
    if (x == y) flag = (A[x] > B[y]);
    else flag = (x > y);

    // using this flag, we can determine order of operations
    // (this flag can also be used to return whether
    // the array is negative)
    List<byte> array = new List<byte>(flag?A:B);
    int len = flag ? B.Length : A.Length;
    for (int i = 0; i < len; i++)
        array = _sub_(array, flag ? B[i] : A[i], i);

    return array.ToArray();
}
private static List<byte> _sub_(List<byte> A, byte b, int idx, byte rem = 0)
{
    short sample = 0;
    if (idx < A.Count)
    {
        sample = (short)((short)A[idx] - (short)b);
        A[idx] = (byte)(sample % 256);
        rem = (byte)(Math.Abs((sample - A[idx])) % 255);
        if (rem > 0)
            return _sub_(A, (byte)rem, idx + 1);
    }
    else A.Add(b);

    return A;
}


Multiplication

public static byte[] Multiply(this byte[] A, byte[] B)
{
    List<byte> ans = new List<byte>();

    
byte ov, res;
    int idx = 0;
    for (int i = 0; i < A.Length; i++)
    {
        ov = 0;
        for (int j = 0; j < B.Length; j++)
        {
            short result = (short)(A[i] * B[j] + ov);

            // get overflow (high order byte)
            ov = (byte)(result >> 8);
            res = (byte)result;
            idx = i + j;

            // apply result to answer array
            if (idx < (ans.Count))
                ans = _add_(ans, res, idx); else ans.Add(res);

        }
        // apply remainder, if any
        if(ov > 0) 
            if (idx+1 < (ans.Count)) 
                ans = _add_(ans, ov, idx+1); 
            else ans.Add(ov);
    }

    return ans.ToArray();
}

Division

- on the way -


Modulus

n = n - ( mod * ⌊ n / mod ⌋ )





To be used as follows: (Addition)
byte[] A = new byte[] { 0xFF };
byte[] B = BitConverter.GetBytes(235192);

byte[] C = A.Add(B);


Sunday, June 9, 2013

Ruby on Rails: Working between Ruby and JavaScript Methods

In an attempt to help a friend with a Ruby project, I needed to become familiar with the Rails' way of doing things. Never thought I'd touch the stuff till about two days ago. I must say, that was quite the new experience for me - as I have never programmed before between three different scripting languages under the same project. (Ruby, JavaScript, and HTML5, if that counts)

Anyhow, I ran into a nerve-wrecking conflict in this development voyage: "calling a Ruby method from JavaScript!"

I had probably spent at least 15 hours strait trying to find the answer to this, at the same time as attempting to understand what lines of script did and why I continuously received errors or broken functions - even though my code looked identical to that which I tried from online forums (including the 'read-on' bug-fixes down the forums). FINALLY, today, I believe I stumbled upon a bit o' luck as things were starting to fall into place and just work the way I wanted it to!




  • First things first that I found often in my digging: 'know where an action should be implemented.' Ruby is to Server-Side as JavaScript is to Client-Side. All data on the client-side's page should be gathered and assembled into a 'packet' sent to the server-side method(s).
  • Ajax makes things easier (in my view).

In this example, I will show you how I successfully called a Ruby method from JavaScript.

My Environment:
Hardware: HP Z1 | Xeon | Quadro 500 | 4DDR3
OS/Version: Windows 7 Professional 64-bit
Ruby Version1.9.3p392
Rails Version3.2.13
Browser/VersionChrome 27.0.1453.110 m

  1. In your console, type: rails new your_project_name followed by cd your_project_name
  2. In your console, type: rails generate controller home index
  3. Navigate to app > views > home and open index.html.erb in Notepad (or preferred editor)
  4. Navigate to config and open routes.rb in Sublime Text 2 (or preferred editor)
  5. Navigate to app > controllers and open home_controller.rb in Sublime Text 2 (or preferred editor)
  6. In index.html.erb, add the following lines:

  7. <script type="text/javascript">
    function func()
    {
        // get user input from text field
        nm = $('input[id=numeric]').val();
        // call ruby method and send input as a 'data' parameter
        // {data:nm} is the equivalent to :data => nm
        // and can also be written as {value:nm} or {myinput:nm}
        $.post("fetchInput", {data:nm}, function(data)
        {
            alert(data);
        });
    }
    </script>
    
    <%= text_field_tag("numeric", "0", :size => 1) %>
    <!-- This button invokes a JavaScript method instead of a Ruby method as a means of easy and clean code implementation -->
    <%= link_to "<button>Submit</button>".html_safe, 'javascript:void(0);', :onclick => "func()", :id => "button_id", :class => "button_class" %>
  8. In routs.rb, add the following lines:

    your_projectname::Application.routes.draw do
        root :to => "home#index"
    
        # as of Rails 4, match has become deprecated
        # the alternative would be to use key-words 
        # appropriate for the task in this case:
        # post '/fetchInput' => 'home#fetchInput'
        match '/fetchInput' => 'home#fetchInput', :as => 'fetchInput'
    end
  9. In home_controller.rb, add the following lines:

    class HomeController < ApplicationController
    
        def index
            # code executes here on page-loading     end     def fetchInput
            # get variable information passed to this method         # again, :data can also be written as :value or :myinput         # respective to how you passed it in through ajax         # ie: :data from {data:nm}          tokens = params[:data]
            # this line returns the method result as a text object         render :text => tokens     end
    end
  10. In your console, type: rails server
  11. Enter a value into the text field and then click the button to see what happens. If all goes well, a popup window will appear containing the text information you entered.