Binary to integer

By SSIhekill on Jun 01, 2012

Another simple script that I made: This will convert binary into integer form, with output always ranging from 0 to 255.
If you supply a string that is too short, it will be prefixed with the correct number of zeroes to put it into correct form.
If you supply extra, the string is truncated.
If you supply something other than a 0 or 1, it's ignored completely, and does not count toward the length of the processed string.

alias bti {
  if ($1- == $null) return No input
  var %params
  var %vpos 1
  while (%vpos <= $len($1-)) {
    if (($mid($1-, %vpos, 1) == 0) || ($mid($1-, %vpos, 1) == 1)) %params = %params $+ $mid($1-, %vpos, 1)
    inc %vpos
  }
  if ($calc($len(%params) % 8) != 0) {
    if ($len(%params) > 8) {
      echo Extra bits received. Ignoring extra bits.
      %params = $left(%params, $calc($len(%params) - ($len(%params) % 8) ))
    }
    else {
      echo Insufficient bits received. Prefixing with additional bits.
      while ($len(%params) < 8) %params = 0 $+ %params
    }
  }
  %vpos = 1
  var %currval 0
  var %result
  while (%vpos <= $len(%params)) {
    if ($mid(%params, %vpos, 1) == 1) %currval = $calc( %currval + 2 ^ ((8 - %vpos) % 8) )
    if ($calc(%vpos % 8) == 0) {
      %result = %result %currval
      %currval = 0
    }
    inc %vpos
  }
  return %result
}

Comments

Sign in to comment.
SReject   -  Jun 03, 2012

Well now ya know :D

 Respond  
SSIhekill   -  Jun 03, 2012

I actually didn't know that. Though tbh, this snippet was mostly a time filler. :p

 Respond  
SReject   -  Jun 01, 2012

miRC already has this built in: $base()

The basics:
$base(input,baseIn,baseOut)
input -> number representation to be converted
baseIn -> the base of the input (2 for binary, 8 for octal, 10 for decimal, 16 for hex, but can be any base)
baseOut -> the base to convert 2 (2 for binary, 8 for octal,...)

Example:
Binary to Decimal: $base(10,2,10) = 2
Octal to Decimal: $base(10,8,10) = 8
Hex to Decimal: $base(10,16,10) = 16

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.