gpt4 book ai didi

c++ - LITTLE_ENDIAN 机器也将修复 BIG_ENDIAN 代码

转载 作者:行者123 更新时间:2023-11-28 02:22:56 26 4
gpt4 key购买 nike

我有这段遗留代码,我需要在 BIG 和 LITTLE Endian 机器上运行。问题出在 hton() 上。

msg->Mac 是 char Mac[16+1]现有代码:(仅适用于 BIG)

if (sscanf(msg->Mac, "%4hx.%4hx.%4hx", (unsigned short *)&new_mac[0],
(unsigned short *)&new_mac[2],
(unsigned short *)&new_mac[4]) != 3) {
return (ERROR_ADDRESS_TRANSLATION);
}

*(unsigned short *)&new_mac[0] = hton(*(unsigned short *)&new_mac[0]);
*(unsigned short *)&new_mac[2] = hton(*(unsigned short *)&new_mac[2]);
*(unsigned short *)&new_mac[4] = hton(*(unsigned short *)&new_mac[4]);

sprintf((char *)newMac, "%04x.%04x.%04x", *(unsigned short *)&new_mac[0],
*(unsigned short *)&new_mac[2], *(unsigned short *)&new_mac[4]);

/* Get the MAC address */
if (sscanf((char *)newMac, "%4hx.%4hx.%4hx", (unsigned short *)&mac_addr[0],
(unsigned short *)&mac_addr[2],
(unsigned short *)&mac_addr[4]) != 3) {
return (ERROR_ADDRESS_TRANSLATION);
}


/* Convert to network order */
*(unsigned short *)&mac_addr[0] = hton(*(unsigned short *)&mac_addr[0]);
*(unsigned short *)&mac_addr[2] = hton(*(unsigned short *)&mac_addr[2]);
*(unsigned short *)&mac_addr[4] = hton(*(unsigned short *)&mac_addr[4]);

为了在 LITTLE Endian 机器上解决这个问题,我使用了一个 SWAP 宏,它可以在短时间内交换字节。这是正确的方法吗?

我在上面添加的代码:(使其也适用于 LITTLE)

#if __BYTE_ORDER != __BIG_ENDIAN

*(unsigned short *)&mac_addr[0] = SWAP(*(unsigned short *)&mac_addr[0]);
*(unsigned short *)&mac_addr[2] = SWAP(*(unsigned short *)&mac_addr[2]);
*(unsigned short *)&mac_addr[4] = SWAP(*(unsigned short *)&mac_addr[4]);

#endif

最佳答案

你在小端机器上测试过吗?由于 hton 已经考虑了拱字节性:

/* Copyright (C) 1993-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.

The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */

#include <stdint.h>
#include <netinet/in.h>

#undef htonl
#undef ntohl

uint32_t
htonl (uint32_t x)
{
#if BYTE_ORDER == BIG_ENDIAN
return x;
#elif BYTE_ORDER == LITTLE_ENDIAN
return __bswap_32 (x);
#else
# error "What kind of system is this?"
#endif
}
weak_alias (htonl, ntohl)

关于c++ - LITTLE_ENDIAN 机器也将修复 BIG_ENDIAN 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31723227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com