Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to get each byte of an integer in C language

Shulou Source: shulou.com Published: 2022-06-02 05:12:32 10月02日 Update

This article mainly explains "how C language gets each byte of integer". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. let's go deep into the train of thought of the editor. Let's study and learn how C language gets each byte of integer.

Method 1: structure & Joint # include

Typedef unsigned int uint32_t

Typedef unsigned char uint8_t

Union bit32_data

{

Uint32_t data

Struct

{

Uint8_t byte0

Uint8_t byte1

Uint8_t byte2

Uint8_t byte3

} byte

}

Int main (void)

{

Union bit32_data num

Num.data = 0x12345678

Printf ("byte0 = 0x%x\ n", num.byte.byte0)

Printf ("byte1 = 0x%x\ n", num.byte.byte1)

Printf ("byte2 = 0x%x\ n", num.byte.byte2)

Printf ("byte3 = 0x%x\ n", num.byte.byte3)

Return 0

}

Running result:

The disadvantage of this method is that it will be affected by the size of the end. It can only be used slightly if the size of the end is clear. The above is the result of running in small-end mode. The structure-federation method is not only useful in obtaining each byte of data, but also useful in data protocol, data bit splitting, etc., and then share it in more detail. Method 2: shift operation # include

# define GET_LOW_BYTE0 (x) ((x > > 0) & 0x000000ff) / * get the 0th byte * /

# define GET_LOW_BYTE1 (x) ((x > 8) & 0x000000ff) / * get the first byte * /

# define GET_LOW_BYTE2 (x) ((x > > 16) & 0x000000ff) / * get the second byte * /

# define GET_LOW_BYTE3 (x) ((x > 24) & 0x000000ff) / * get the third byte * /

Int main (void)

{

Unsigned int a = 0x12345678

Printf ("byte0 = 0x%x\ n", GET_LOW_BYTE0 (a))

Printf ("byte1 = 0x%x\ n", GET_LOW_BYTE1 (a))

Printf ("byte2 = 0x%x\ n", GET_LOW_BYTE2 (a))

Printf ("byte3 = 0x%x\ n", GET_LOW_BYTE3 (a))

Return 0

}

Running result:

This is also the most common and effective way to get each byte of data. This similar bit operation is widely used in embedded systems, such as representing pixel color values in LCD operations, FLASH operations, and so on. Thank you for your reading, the above is the content of "how C language gets each byte of integers". After the study of this article, I believe you have a deeper understanding of how C language gets each byte of integers. The specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Bytes integers languages data methods aspects results learning running content size situation useful end-to-end structure union practical effective not only in the table Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Tech Info MySQL Linux Microsoft