Search code examples
javascriptperlpack

javascript Perl pack


First, I'll tell you I cannot speak English, but I want to try and get information of how to implement a Perl pack into Javascript to make a node.js module.

To do that, I would like to get more information about the Perl pack. In particular, the information I especially want to know "C, H *, N".

Also, if I could get more information on jspack, that would be wonderful.

Thank you in advance.

What I actually tried.

However, it didn't work.

日本語(Japan)


Solution

  • pack 'C', pack 'N' and pack 'H*' are used to create a sequence of bytes.

    my $bytes = pack('C', $uint8);
    
    # Array of bytes
    var bytes = [];
    bytes.push(uint8);
    
    # String of bytes
    var bytes = "";
    bytes += String.fromCharCode(uint8);
    

    my $bytes = pack('N', $uint32);
    
    # Array of bytes
    var bytes = [];
    bytes.push((uint32 >> 24) & 0xFF);
    bytes.push((uint32 >> 16) & 0xFF);
    bytes.push((uint32 >>  8) & 0xFF);
    bytes.push((uint32      ) & 0xFF);
    
    # String of bytes
    var bytes = "";
    bytes += String.fromCharCode((uint32 >> 24) & 0xFF);
    bytes += String.fromCharCode((uint32 >> 16) & 0xFF);
    bytes += String.fromCharCode((uint32 >>  8) & 0xFF);
    bytes += String.fromCharCode((uint32      ) & 0xFF);
    

    my $bytes = pack('H*', $hex_str);
    
    # Array of bytes
    function hexToBytes(hex) {
        var bytes = [];
        for (var c = 0; c < hex.length; c += 2)
           bytes.push(parseInt(hex.substr(c, 2), 16));
    
        return bytes;
    }
    
    # String of bytes
    function hexToBytes(hex) {
        var bytes = "";
        for (var c = 0; c < hex.length; c += 2)
           bytes += String.fromCharCode(parseInt(hex.substr(c, 2), 16));
    
        return bytes;
    }