Skip to content

Commit

Permalink
Convert single hex char to integer
Browse files Browse the repository at this point in the history
  • Loading branch information
James Sanderson committed Aug 23, 2014
0 parents commit 9dbfe80
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/target
/Cargo.lock
/*.iml
/.idea
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "crypto"
version = "0.0.1"
authors = ["zofrex"]

[[bin]]

name = "hex_to_base64"
Binary file added hex_to_base64
Binary file not shown.
31 changes: 31 additions & 0 deletions src/hex.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
pub fn hex_to_dec(hex: char) -> int {
if hex >= '0' && hex <= '9' {
hex as int - '0' as int
}
else if hex >= 'a' && hex <= 'f' {
hex as int - 'a' as int + 10
}
else {
fail!("Character {} out of range", hex);
}
}

#[test]
fn all_hexes() {
let hexes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
for i in range(0u, hexes.len()) {
assert_eq!(hex_to_dec(hexes[i]), i as int);
}
}

#[test]
#[should_fail]
fn test_too_large() {
hex_to_dec('g');
}

#[test]
#[should_fail]
fn test_too_small() {
hex_to_dec('/');
}
5 changes: 5 additions & 0 deletions src/hex_to_base64.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod hex;

fn main() {
println!("Output: {}", hex::hex_to_dec('0'));
}

0 comments on commit 9dbfe80

Please sign in to comment.