Convert 2 bytes into an integer

后端 未结 4 804
挽巷
挽巷 2021-02-12 19:00

I receive a port number as 2 bytes (least significant byte first) and I want to convert it into an integer so that I can work with it. I\'ve made this:

char buf[         


        
相关标签:
4条回答
  • 2021-02-12 19:36

    I appreciate this has already been answered reasonably. However, another technique is to define a macro in your code eg:

    // 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;
    }
    
    0 讨论(0)
  • 2021-02-12 19:41
    char buf[2]; //Where the received bytes are
    int number;
    number = *((int*)&buf[0]);
    

    &buf[0] takes address of first byte in buf.
    (int*) converts it to integer pointer.
    Leftmost * reads integer from that memory address.

    If you need to swap endianness:

    char buf[2]; //Where the received bytes are
    int number;  
    *((char*)&number) = buf[1];
    *((char*)&number+1) = buf[0];
    
    0 讨论(0)
  • 2021-02-12 19:53

    If you make buf into an unsigned char buf[2], you could just simplify it to;

    number = (buf[1]<<8)+buf[0];
    
    0 讨论(0)
  • 2021-02-12 19:57

    I receive a port number as 2 bytes (least significant byte first)

    You can then do this:

      int number = buf[0] | buf[1] << 8;
    
    0 讨论(0)
提交回复
热议问题