Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a hexadecimal string to a decimal integer

Tags:

parsing

hex

rust

I'm writing a Rust program that reads off of an I2C bus and saves the data. When I read the I2C bus, I get hex values like 0x11, 0x22, etc.

Right now, I can only handle this as a string and save it as is. Is there a way I can parse this into an integer? Is there any built in function for it?

like image 735
tsf144 Avatar asked Sep 03 '15 16:09

tsf144


People also ask

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

How do you convert hexadecimal numbers to decimal numbers?

This is simple algorithm where you have to multiply positional value of binary with their digit and get the sum of these steps. Example-1 − Convert hexadecimal number ABCDEF into decimal number. = (10485760+720896+49152+3328+224+15)10 = (11259375)10 which is answer. Example-2 − Convert hexadecimal number 1F.

How do you convert hex to int in Python?

The most common and effective way to convert hex into an integer in Python is to use the type-casting function int() . This function accepts two arguments: one mandatory argument, which is the value to be converted, and a second optional argument, which is the base of the number format with the default as 10 .


1 Answers

In most cases, you want to parse more than one hex byte at once. In those cases, use the hex crate.

parse this into an integer

You want to use from_str_radix. It's implemented on the integer types.

use std::i64;  fn main() {     let z = i64::from_str_radix("1f", 16);     println!("{:?}", z); } 

If your strings actually have the 0x prefix, then you will need to skip over them. The best way to do that is via trim_start_matches:

use std::i64;  fn main() {     let raw = "0x1f";     let without_prefix = raw.trim_start_matches("0x");     let z = i64::from_str_radix(without_prefix, 16);     println!("{:?}", z); } 
like image 125
Shepmaster Avatar answered Sep 27 '22 19:09

Shepmaster