Categories
Uncategorized

Discrete Math code

/*
 * Brian Abbott
 * Math 2130
 * BF Prompt
 *
 * This code produces the following output:
 *
 * 1011011111000101 in base 8 is 133705
 * 1011011111000101 in base 16 is B7C5
 */

let base2Num = '1011011111000101', base8Num = '', base16Num = '', temp = 0, numbers = []

/*
  The code below converts Base 2 to Base 8
 */

for (let i = base2Num.length; i > 0; i -= 3) {
  numbers = [parseInt(base2Num[i - 1]), parseInt(base2Num[i - 2]), parseInt(base2Num[i - 3])]
  for (let j = 0; j < 3; j++) {
    if (!isNaN(numbers[j]))
      temp += numbers[j] * Math.pow(2, j)
  }
  base8Num = temp.toString() + base8Num
  temp = 0
}

console.log(base2Num + ' in base 8 is ' + base8Num)

/*
  The code below converts Base 2 to Base 16
 */

for (let i = base2Num.length; i > 0; i -= 4) {
  numbers = [parseInt(base2Num[i - 1]), parseInt(base2Num[i - 2]), parseInt(base2Num[i - 3]), parseInt(base2Num[i - 4])]
  for (let j = 0; j < 4; j++) {
    if (!isNaN(numbers[j]))
      temp += numbers[j] * Math.pow(2, j)
  }
  base16Num = (temp > 9) ? getHexLetter(temp) + base16Num : temp.toString() + base16Num
  temp = 0
}

console.log(base2Num + ' in base 16 is ' + base16Num)

function getHexLetter(num) {
  let letter
  switch (num) {
    case 10:
      letter = 'A'
      break
    case 11:
      letter = 'B'
      break
    case 12:
      letter = 'C'
      break
    case 13:
      letter = 'D'
      break
    case 14:
      letter = 'E'
      break
    case 15:
      letter = 'F'
      break
    default:
      letter = 'ERROR'
  }
  return letter
}

Leave a Reply

Your email address will not be published. Required fields are marked *