整数 return 值的按位算术

Bitwise arithmetic on an integer return value

这里我们有一个 fire() 函数,它接受两个参数:

return 代码将是:

半伪代码解释:

//r is A ... (A + BS_GRID_ROWS - 1)
//c is 1 ... BS_GRID_COLS

fire(char r, int c) {
    //some set of commands

    if(miss) {
        return 0;
    else if(sink) {
        return hit + sunk + size;
    else if(hit) {
        return hit;
    else {
        return miss;
    }
}

我不确定如何从 return 值中提取这些单独的值(命中、沉没、大小)。

实际的 .h 文件及其相关的 const 值见此处:

#ifndef BATTLESHIP
#define BATTLESHIP
const int BS_SHIP_HIT  = 0x10;  // Ship is hit, or
const int BS_SHIP_SANK = 0x20; // sank (must also | BS_SHIP_HIT)
const int BS_CARRIER   = 1;
const int BS_BATTLESHIP= 2;
const int BS_CRUISER   = 3;
const int BS_DESTROYER = 4;
const int BS_SUBMARINE = 5;
const int BS_SHIP_COUNT = 5;
const int BS_SHIP_MASK = 0x0F;
const int BS_CARRIER_SIZE   = 5;
const int BS_BATTLESHIP_SIZE= 4;
const int BS_CRUISER_SIZE   = 3;
const int BS_DESTROYER_SIZE = 2;
const int BS_SUBMARINE_SIZE = 3;
const int BS_MODE_NEW_GAME   = 1;
const int BS_MODE_CONTINUE_GAME = 2;
const int BS_GRID_ROWS = 10; // letters A to J
const int BS_GRID_COLS = 10; // numbers 1 to 10
const int MaxPlayerCount = 65; // Maximum size for following arrays
extern int userIncoming(char, int);
extern int userBattle(int, int);
extern int incomingStub(char, int);
extern int battleStub(int, int);
extern int (*fire[])(char, int);
extern int (*battleship[])(int, int);
extern char const *playerName[];
#endif

也许是这样的?

int result = fire(r, c);
if (result & BS_SHIP_HIT)
{
    std::cout << "Ship of size " << result & BS_SHIP_MASK << " hit\n";
}

如果在result中设置了BS_SHIP_HIT位,result & BIT_SHIP_HIT的结果将等于BS_SHIP_HIT,否则结果将为零(等价于为假)。

result & BS_SHIP_MASK的结果将是result的低四位。


或者让我们使用实际位来查看它:

BS_SHIP_HIT 等于二进制值 00010000BS_SHIT_MASK 等于 00001111。让我们假设 fire returns 00010101BS_SHIP_HIT 设置和大小 5),那么 if 条件将是

  00010000
& 00010101
----------
= 00010000

那么对于打印,表达式将是

  00010101
& 00001111
----------
= 00000101