异或运算小记

82 阅读1分钟

简介

"异或运算"(XOR)主要用来判断两个值是否不同。

XOR 一般使用插入符号(caret)^表示。如果约定0 为 false,1 为 true,那么 XOR 的运算真值表如下。

0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0

规律

  • 一个值与自身的运算,总是为 false。
x ^ x = 0
  • 一个值与 0 的运算,总是等于其本身。
x ^ 0 = x
  • 可交换性
x ^ y = y ^ x
  • 结合性
x ^ (y ^ z) = (x ^ y) ^ z

应用

要求从网口0收到的报文转发到网口1,从网口1收到的报文转发到网口0;其他2->3,3->2类似处理。

rx为port,tx使用port^1即可实现

for (;;) {
		/*
		 * Receive packets on a port and forward them on the paired
		 * port. The mapping is 0 -> 1, 1 -> 0, 2 -> 3, 3 -> 2, etc.
		 */
		RTE_ETH_FOREACH_DEV(port) {

			/* Get burst of RX packets, from first port of pair. */
			struct rte_mbuf *bufs[BURST_SIZE];
			const uint16_t nb_rx = rte_eth_rx_burst(port, 0,
					bufs, BURST_SIZE);

			if (unlikely(nb_rx == 0))
				continue;

			/* Send burst of TX packets, to second port of pair. */
			const uint16_t nb_tx = rte_eth_tx_burst(port ^ 1, 0,
					bufs, nb_rx);

			/* Free any unsent packets. */
			if (unlikely(nb_tx < nb_rx)) {
				uint16_t buf;
				for (buf = nb_tx; buf < nb_rx; buf++)
					rte_pktmbuf_free(bufs[buf]);
			}
		}
	}