Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. fn main() {
  2. // edit this value for your decimal input
  3. let input = "85.125";
  4. let mut split = input.split('.');
  5.  
  6. let integer = split.next().unwrap().parse::<i32>().unwrap();
  7. let (decimal, decimal_len) = if let Some(x) = split.next() {
  8. (x.parse::<i32>().unwrap(), x.len() as i32)
  9. } else {
  10. (0, 1)
  11. };
  12.  
  13. let mut bits = [0; 32];
  14.  
  15. bits[0] = if integer.signum() < 0 {
  16. 1
  17. } else {
  18. 0
  19. };
  20.  
  21. let mut int_buf = [0; 32];
  22. let mut dec_buf = [0; 16];
  23.  
  24. let pow = to_binary_int(integer, &mut int_buf[..]) - 1;
  25. to_binary_dec(decimal as f64 / 10.0_f64.powi(decimal_len), &mut dec_buf[..]);
  26.  
  27. let exp = 127 + pow;
  28. to_binary_int(exp as i32, &mut bits[1..9]);
  29.  
  30. copy_slice (&mut bits[9..10 + pow], &int_buf[int_buf.len() - pow..]);
  31. copy_slice (&mut bits[pow + 10..], &dec_buf[..]);
  32.  
  33. println!("{:?}", bits);
  34. }
  35.  
  36. fn copy_slice(target: &mut [i32], from: &[i32]) {
  37. target[..from.len()].iter_mut().zip(from.iter()).for_each(|x| {
  38. *x.0 = *x.1;
  39. });
  40. }
  41.  
  42. fn to_binary_int(num: i32, buf: &mut [i32]) -> usize {
  43. let mut cur = num;
  44. let mut i = 0;
  45. while cur > 0 {
  46. let rem = cur % 2;
  47. cur /= 2;
  48. buf [i] = rem;
  49. i += 1;
  50. }
  51. buf.reverse();
  52. i
  53. }
  54.  
  55. fn to_binary_dec(num: f64, buf: &mut [i32]) {
  56. let mut cur = num;
  57. let mut precision = Some(buf.len());
  58.  
  59. let mut i = 0;
  60.  
  61. while let Some(p) = precision {
  62. if p == 0 {
  63. precision = None;
  64. } else {
  65. cur *= 2.0;
  66. let bit = if cur as i32 == 1 {
  67. cur -= 1.0;
  68. 1
  69. } else {
  70. 0
  71. };
  72. buf[i] = bit;
  73.  
  74. i += 1;
  75. precision = Some(p - 1);
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement