fork download
  1. (defun f (x &optional (length 1))
  2. (if (integerp x)
  3. (loop with bits = '()
  4. for (q r) = (multiple-value-list (floor x 2))
  5. then (multiple-value-list (floor q 2))
  6. repeat (max length (1+ (integer-length x)))
  7. do (push r bits)
  8. finally (return (if (and (eql x -1) (eql length 1))
  9. (cons 1 bits)
  10. bits)))
  11. (destructuring-bind (sign-bit . bits) x
  12. (loop for b in (if (zerop sign-bit)
  13. bits
  14. (mapcar (lambda (x) (logxor x 1)) bits))
  15. for i downfrom (1- (length bits))
  16. sum (* b (expt 2 i)) into n
  17. finally (return (if (zerop sign-bit) n (- (1+ n))))))))
  18.  
  19. (loop for args in '((10)
  20. (10 8)
  21. (-8)
  22. (-8 8)
  23. (-1)
  24. nil
  25. ((0 1 1 1))
  26. ((1 1 1 1))
  27. ((1 0 0 0))
  28. nil
  29. (1)
  30. (1 1)
  31. (1 2)
  32. (-1)
  33. (-1 1)
  34. (-1 2)
  35. nil
  36. ((0 1))
  37. ((1))
  38. ((1 1))
  39. nil
  40. (0)
  41. ((0)))
  42. do (if args
  43. (format t "~{~S~^, ~}~10T-> ~S~%" args (apply #'f args))
  44. (terpri)))
  45.  
Success #stdin #stdout 0.03s 10680KB
stdin
Standard input is empty
stdout
10        -> (0 1 0 1 0)
10, 8     -> (0 0 0 0 1 0 1 0)
-8        -> (1 0 0 0)
-8, 8     -> (1 1 1 1 1 0 0 0)
-1        -> (1 1)

(0 1 1 1) -> 7
(1 1 1 1) -> -1
(1 0 0 0) -> -8

1         -> (0 1)
1, 1      -> (0 1)
1, 2      -> (0 1)
-1        -> (1 1)
-1, 1     -> (1 1)
-1, 2     -> (1 1)

(0 1)     -> 1
(1)       -> -1
(1 1)     -> -1

0         -> (0)
(0)       -> 0