22

ポート番号を 2 バイト (最下位バイトが最初) として受け取り、それを操作できるように整数に変換したいと考えています。私はこれを作った:

char buf[2]; //Where the received bytes are

char port[2];

port[0]=buf[1]; 

port[1]=buf[0];

int number=0;

number = (*((int *)port));

ただし、正しいポート番号を取得できないため、何か問題があります。何か案は?

4

4 に答える 4

7

これはすでに合理的に回答されていることに感謝します。ただし、コードでマクロを定義する別の手法もあります。

// bytes_to_int_example.cpp
// Output: port = 514

// I am assuming that the bytes the bytes need to be treated as 0-255 and combined MSB -> LSB

// This creates a macro in your code that does the conversion and can be tweaked as necessary
#define bytes_to_u16(MSB,LSB) (((unsigned int) ((unsigned char) MSB)) & 255)<<8 | (((unsigned char) LSB)&255) 
// Note: #define statements do not typically have semi-colons
#include <stdio.h>

int main()
{
  char buf[2];
  // Fill buf with example numbers
  buf[0]=2; // (Least significant byte)
  buf[1]=2; // (Most significant byte)
  // If endian is other way around swap bytes!

  unsigned int port=bytes_to_u16(buf[1],buf[0]);

  printf("port = %u \n",port);

  return 0;
}
于 2016-07-17T03:14:28.413 に答える