bit-manipulation - 操作任何值类型的位

标签 bit-manipulation d bit phobos

是否有人编写了一些扩展 core.bitop 的通用函数?位操作适用于任何值类型?

就像是

bool getBit(T)(in T a, int bitnum); // bt
T setBit(T)(in T a, int bitnum); // bts
auto ref setBitInPlace(T)(ref T a, int bitnum);

我知道这相对容易实现,所以我很好奇它为什么还没有 Phobos。

更新:

这是我第一次尝试:
bool getBit(T, I)(in T a, I bitnum) @safe pure nothrow if (isIntegral!T &&
                                                           isIntegral!I) {
    return a & (((cast(I)1) << bitnum)) ? true : false;
}

bool getBit(T, I)(in T a, I bitnum) @trusted pure nothrow if ((!(isIntegral!T)) &&
                                                              isIntegral!I) {
    enum nBits = 8*T.sizeof;
    static      if (nBits ==  8) alias I = ubyte;
    else static if (nBits == 16) alias I = ushort;
    else static if (nBits == 32) alias I = uint;
    else static if (nBits == 64) alias I = ulong;
    return (*(cast(I*)&a)).getBit(bitnum); // reuse integer variant
}
alias bt = getBit;

我的想法是制作getBit适用于所有具有值语义的类型。这就是为什么我需要 Actor 阵容(我认为)。是否有特征来检查类型是否具有值语义?

还有一个特征来检查类型是否支持特定操作,例如按位和 & ?我总是可以使用 __traits(compiles, ...)但标准化是好的。

为了让它变得更好,我想我需要为支持位操作的 T 显式重载,以便使这个变体 @safe 正确吗?在我上面的通用解决方案中,我需要 cast这就是@unsafe。

另见:http://forum.dlang.org/thread/tekrnzkemcbujbivvfpv@forum.dlang.org#post-tekrnzkemcbujbivvfpv:40forum.dlang.org

最佳答案

Is there a traits to check if a type has value semantics or not?



值类型没有特征,至少在 the documentation 中没有。
但是,在使用“is 表达式”之前,我已经检查了值类型:
import std.stdio;

struct Foo {}

auto fn(T)(T type)
{
    static if (is(T == struct)) {
        writeln(T.stringof ~ " is a value type");   
    } else if (is(T == class)) {
        writeln(T.stringof ~ " is a reference type");   
    } else {
        writeln(T.stringof ~ " is something else"); 
    }
}

void main()
{
    Foo f;

    fn(f);
    fn(new Object());
    fn(1);
}

Also is there a trait to check if a type supports a specific operation such as bitwise and &?



除了编译的特征之外,这也可以通过 is 表达式来实现。这类似于目前为 ranges, for example 所做的工作。 :
import std.stdio;

struct Foo {
    auto opBinary(string op)(Foo rhs) 
        if (op == "&")
    {
        return rhs.init; // dummy implementation
    }
};

template canUseBitOps(T)
{
    enum bool canUseBitOps = is(typeof(
    (inout int = 0)
    {
        T t1 = T.init;
        T t2 = T.init;
        auto r = t1 & t2;
    }));
}

void main()
{
    assert(canUseBitOps!int);
    assert(!canUseBitOps!string);
    assert(canUseBitOps!Foo);
}

关于bit-manipulation - 操作任何值类型的位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21368664/

相关文章:

Java : Operators and Typecasting

optimization - 将整数除以 3 的最快方法是什么?

d - D 中的单线程 future / promise ?

D Lang 文件观察器

C - 如何在内存级别进行算术转换?

c++ - (n&1) 和 n&1 之间的区别

algorithm - 获得整数的最高十进制数字的最快方法是什么?

multithreading - 无需等待即可在线程之间发送消息

python - 在 Python 中生成一个 n 长度的位列表

C - 有什么方法可以使用位检查来检查数字是否等于 1?