问题
Is there a tutorial somewhere that explains on which datatypes bitwise operations can be used? I don't know why Lady Ada thinks that I cannot bitwise OR two Standard.Integer...
$ gnatmake test.adb
gcc -c test.adb
test.adb:50:77: there is no applicable operator "Or" for type "Standard.Integer"
gnatmake: "test.adb" compilation error
Really? I excused the compiler for not being able to AND/OR enumerated data types. I excused the compiler for not being able to perform bitwise operations on Character type. I excused the compiler for not being able to convert from Unsigned_8 to Character in what I thought was the obvious way. But this is inexcusable.
回答1:
No one seems to want to just come out and answer the damn question:
Ada doesn't provide logical (bit-wise) operations on integer types, it provides them on modular types. Here's the section in the reference manual.
回答2:
The "and"
, "or"
, and "xor"
operators are defined for Boolean
, for modular types, and for one-dimensional arrays of Boolean
.
The language could have defined them for signed integer types, but that would create confusion given the variety of ways that signed integers can be represented. (Most implementations use two's-complement, but there are other possibilities.)
If you insist, you could define your own overloaded "or"
operator, such as:
function "or"(Left, Right: Integer) return Integer is
type Unsigned_Integer is mod 2**Integer'Size;
begin
return Integer(Unsigned_Integer(Left) or Unsigned_Integer(Right));
end "or";
(I've verified that this compiles, but I haven't tested it, and I'd expect it to fail for negative values.)
But if you need to perform bitwise operations, you're better off using modular types or arrays of Boolean
rather than signed integers.
来源:https://stackoverflow.com/questions/18365473/bitwise-operations-in-ada