You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.1 KiB

  1. use clap::App;
  2. use termion::{color, style};
  3. extern crate base64;
  4. extern crate hex;
  5. extern crate num_bigint;
  6. extern crate num_traits;
  7. use num_bigint::{BigInt, Sign};
  8. fn main() {
  9. let matches = App::new("myapp")
  10. .version("0.0.1")
  11. .about("Convert between string formats.\nhttps://github.com/arnaucube/konv")
  12. .arg("<INPUT> 'Value to parse'")
  13. .arg("-b 'Read input in BigEndian (by default uses LittleEndian)'")
  14. .get_matches();
  15. let inp = matches.value_of("INPUT").unwrap();
  16. println!("input {}", inp);
  17. let r: BigInt;
  18. if inp.starts_with("0x") {
  19. r = d_hex(inp, matches.is_present("b"));
  20. } else {
  21. r = d_dec(inp, matches.is_present("b"));
  22. }
  23. // print decimal
  24. println!(
  25. " dec {}{}{}",
  26. color::Fg(color::Yellow),
  27. r.to_string(),
  28. style::Reset
  29. );
  30. // print hexadecimal
  31. println!(
  32. " hex {}{}{}",
  33. color::Fg(color::Blue),
  34. r.to_str_radix(16),
  35. style::Reset
  36. );
  37. // print base64
  38. let (_, byt) = r.to_bytes_be();
  39. let b64 = base64::encode(&byt);
  40. println!(" b64 {}{}{}", color::Fg(color::Cyan), b64, style::Reset);
  41. // print bytes
  42. let mut byte_str: String = byt[0].to_string();
  43. for x in byt.iter().skip(1) {
  44. byte_str = format!("{}, {}", byte_str, x);
  45. }
  46. println!(" byt [{}]", byte_str);
  47. }
  48. fn d_hex(raw_inp: &str, bigendian: bool) -> BigInt {
  49. let inp;
  50. if raw_inp.starts_with("0x") {
  51. inp = raw_inp.trim_start_matches("0x");
  52. } else {
  53. inp = raw_inp;
  54. }
  55. let b = hex::decode(inp).expect("Decoding failed");
  56. let bi: BigInt;
  57. if bigendian {
  58. bi = BigInt::from_bytes_be(Sign::Plus, &b);
  59. } else {
  60. bi = BigInt::from_bytes_le(Sign::Plus, &b);
  61. }
  62. bi
  63. }
  64. fn d_dec(inp: &str, bigendian: bool) -> BigInt {
  65. let or = BigInt::parse_bytes(inp.as_bytes(), 10).unwrap();
  66. let (_, b) = or.to_bytes_be();
  67. if bigendian {
  68. return BigInt::from_bytes_be(Sign::Plus, &b);
  69. }
  70. BigInt::from_bytes_le(Sign::Plus, &b)
  71. }