static_cast的不同行为

时间:2016-04-07 09:19:46

标签: c++ json casting

我正在尝试将uint64_t转换为uint8_t。我知道这没有任何意义,但由于JSON Library将所有数值转换为uint64_t或int64_t,我必须将其转换回来。我总是确定我没有收到不适合uint8_t的值。

现在,当我在OSx上编译并运行以下代码时,一切都按预期工作。但是一旦我转到Raspberry Pi 2,代码就不再有效了。值为0.

任何人都可以解释为什么会这样吗?有人有更好的解决方案吗?

#include <iostream>

#include "json.h"

using JSON = nlohmann::json;

typedef struct {
    uint8_t boardId;
    uint8_t commandGroupId;
    uint8_t commandId;
} ExternalMessageType;

int main(int argc, const char * argv[])
{
    JSON x;
    ExternalMessageType y;

    x["board-id"] = 1;
    x["command-group-id"] = 1;
    x["command-id"] = 11;

    y.boardId = static_cast<uint8_t>(x["board-id"]);
    y.commandGroupId = static_cast<uint8_t>(x["command-group-id"]);
    y.commandId = static_cast<uint8_t>(x["command-id"]);

    std::cout << "Board: " << (int)y.boardId << std::endl;
    std::cout << "Group: " << (int)y.commandGroupId << std::endl;
    std::cout << "Command: " << (int)y.commandId << std::endl;

    if (y.commandGroupId == 1) {
        std::cout << "Command Group is ok." << std::endl;
        switch (y.commandId) {
            case 11: {
                std::cout << "Speed Message" << std::endl;
            } break;
        }
    } else {
        std::cout << "Command Group is not ok." << std::endl;
    }

    return 0;
}

0 个答案:

没有答案