Web based MIPS assembler and emulator

utils.js 760B

123456789101112131415161718192021222324252627282930313233343536
  1. const error = (error) => console.error(error)
  2. const dec2binu = (dec, length) => {
  3. let unsigned = Math.abs(dec)
  4. let bin = unsigned.toString(2)
  5. if (bin.length >= length) {
  6. return bin
  7. } else {
  8. return '0'.repeat(length - bin.length).concat(bin)
  9. }
  10. }
  11. const hex2bin = (hex, length) => {
  12. if (hex.startsWith('0x')) {
  13. return dec2binu(parseInt(hex.slice(2), 16), length)
  14. } else {
  15. console.error("Hex immediates must start with 0x")
  16. }
  17. }
  18. const bin2hex = (bin, length) => {
  19. let hex = parseInt(bin, 2).toString(16)
  20. if (hex.length >= length) {
  21. return hex
  22. } else {
  23. return '0'.repeat(length - hex.length).concat(hex)
  24. }
  25. }
  26. module.exports = {
  27. 'error': error,
  28. 'dec2binu': dec2binu,
  29. 'hex2bin': hex2bin,
  30. 'bin2hex': bin2hex
  31. }