如何从文字字节表达式构造const整数? [英] How to construct const integers from literal byte expressions?

查看:99
本文介绍了如何从文字字节表达式构造const整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使用字节字符串或构造整数的宏从文字字节表达式构造 const 整数?

Is there a way to construct a const integer from a literal byte expression, either using a byte string or a macro which constructs the integer?

例如:

const MY_ID:   u16 = u16_code!(ID);
const MY_WORD: u32 = u32_code!(WORD);
const MY_LONG: u64 = u64_code!(LONGWORD);

或者类似的方法,传入 b ID 而不是 ID *

Or something similar, passing in b"ID" instead of ID? *

当传递了错误的字符数时,它也应该无法编译,这在使用时我不知道该如何实现

It should fail to compile when the wrong number of characters are passed too, something I couldn't figure out how to achieve when using bit-shifting on a literal byte string.

这是一个简单的示例,可在基本级别上运行,但无法确保

Here's a simple example that works on a basic level, but fails to ensure correctly sized arguments.

// const MY_ID: u16 = u16_code!(b"ID");
#[cfg(target_endian = "little")]
macro_rules! u16_code {
    ($w:expr) => { ((($w[0] as u16) <<  0) | (($w[1] as u16) <<  8)) }
}
#[cfg(target_endian = "big")]
macro_rules! u16_code {
    ($w:expr) => { ((($w[1] as u16) <<  0) | (($w[0] as u16) <<  8)) }
}






* 参见相关问题:是否存在与'stringify'宏等效的字节?

推荐答案

可以为每种类型建立一个宏,方法是索引数组并将部件位移位到正确的位置。您的u16的示例表达式为

You can build a macro for each type by indexing into the array and bitshifting the parts to the correct position. An example expression for your u16 is

((b"ID"[0] as u16) << 8) | (b"ID"[1] as u16)

您可以替换 b ID 由来自 $ e:expr $ e >。

You can replace the b"ID" by a macro replacement $e which comes from a $e:expr.

要实现长度检查,可以将无用的 * $ e插入为[u8; 2] ,如果类型不匹配将无法编译。

To achieve the length check, you can insert a useless *$e as [u8; 2], which will fail to compile if the types don't match.

这篇关于如何从文字字节表达式构造const整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆