将2个字节组合成C中的short int

时间:2017-04-16 04:21:26

标签: c network-programming int hex bit-shift

我通过网络数据包收到一个短的int,这意味着它将以网络字节顺序(大端)的2个字节。

我想将我收到的两个字节组合到我的机器上的一个short int变量中,这是一个小字节顺序。

示例:

short int test = 400; //0x190 in big endian, 0x9001 in little endian
char testResponse[2] = {0x01, 0x90};
//here is my attempt
short int result = testResponse[1] << 8 | testResponse[0];
printf("%d\n", result); //-28671 when expecting 400

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

#include <arpa/inet.h>
#include <string.h>

int16_t result;
memcpy(&result, testResponse, sizeof(int16_t));
result = (int16_t)ntohs((uint16_t)result);
某些平台,例如32位手臂,不允许未对齐的访问。因此,在调用ntoh之前,请使用memcpy将其调整为正确大小的int。

答案 1 :(得分:0)

你把这些指数搞糊涂了。小端的数字是0x0190,但是你的代码计算的是大端数,class MainViewController: UIViewController { @IBOutlet weak var contentTable: PagingTableView! var legumes: [String] = ["Eggs", "Milk", "Chocolat", "Web", "Miel", "Pop", "Eco", "Moutarde", "Mayo", "Thea", "Pomelade", "Gear", "Etc" , "Nop", "Dews", "Tout", "Fun", "Xen" , "Yoga" ] override func viewDidLoad() { super.viewDidLoad() contentTable.dataSource = self contentTable.pagingDelegate = self } } extension MainViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return legumes.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ImageTableViewCell guard legumes.indices.contains(indexPath.row) else { return cell } cell.content = legumes[indexPath.row] return cell } } extension MainViewController: PagingTableViewDelegate { func paginate(_ tableView: PagingTableView, to page: Int) { contentTable.isLoading = true DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.legumes.append(contentsOf: legumes) self.contentTable.isLoading = false } } } ,在有符号的短路中,在左移到符号位时也会导致整数溢出。

由于0x9001可能已签名或未签名,因此代码确实不具备可移植性。虽然大多数架构可能都有未签名的字符,但事实是大多数C程序都是为签名的char架构 - x86编写的。事实上,0x90符号扩展可能会导致意外的结果。

因此更便携

char