How would I store hexedecimal values in a variable?

extern crate hex;

fn main()
{
    let blue: u32 = hex::decode("0c1047"); // Error over here
}

So I want blue to store #0c1047 this hexadecimal value inside blue (here is the color picker site https://duckduckgo.com/?q=color+picker&t=hk&ia=answer. Is there a way to directly store hexadecimal values or do I have to store it in a decoded fashion or something.

Additonally to store an rgb value I have to declare u32 bits of memory, am I correct?

1 Like

0x0c1047 is just a way of writing a number. Computers store them in a binary format anyway, so your options are to store it as a hex-string (not a number) or parse it into 3 u8 numbers and store them.

let hex = "0c1047";
let r = u8::from_str_radix(&hex[0..2], 16).unwrap();
let g = u8::from_str_radix(&hex[2..4], 16).unwrap();
let b = u8::from_str_radix(&hex[4..6], 16).unwrap();
let color = (r, g, b);
1 Like

Thanks mate. Just curious why do we need this 0x before specifying the hex value?

For example,

mod color {
    use std::fmt;

    pub struct Color (u32);

    impl Color {
        pub fn from_hex_str(s: &str) -> Self {
            Self(u32::from_str_radix(s,16).unwrap())
        }
    }

    impl fmt::Display for Color {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{:06x}", self.0)
        }
    }
}

use color::Color;

fn main() {
    let blue = Color::from_hex_str("0c1047");
    println!("{}",blue);
}
1 Like

When I write 123 you assume it is in decimal notation. If a number is not prefixed, it is base-10.
For the other bases there are

  • 0x for base-16 (hexadecimal)
  • 0b for base-2 (binary)
  • 0o for base-8 (octal)
2 Likes

Just to make it explicit in case you don't know. If your value is not provided as string you can write hex-literals directly in your source code, e.g.

let dec: u32 = 15;
let hex: u32 = 0xF;
let bin: u32 = 0b1111;
let oct: u32 = 0o17;

assert_eq!(dec, hex);
assert_eq!(hex, bin);
assert_eq!(bin, oct);
assert_eq!(oct, dec);

You can also include _ in numeric literals to do some separation. Furthermore, you can include the datatype in numeric literals:

let dec = 65_536u32;
let dec2 = 65536_u32;
let hex: u32 = 0x0001_0000;

assert_eq!(dec, dec2);
assert_eq!(dec2, hex);
assert_eq!(hex, dec);
2 Likes

Just a quick question, how do I output an u32 variable as hex if I am printing the value on the console?

println!("{:x}", 123);

This will print:

7b

You can also use an upper case X to print the hexadecimal in uppercase.

2 Likes

And for more info, check the docs for std::fmt module, this part in particular.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.