<!DOCTYPE html>
    <html lang="vi" xmlns="http://www.w3.org/1999/xhtml" prefix="og: http://ogp.me/ns#">
    <head>
<title>Trường Bit trong C</title>
<meta name="description" content="Trường Bit trong C - Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;www.nguoicodonvn2008.info&#x002F;vi&#x002F;news&#x002F;savefile&#x002F;kien-thuc-may-tinh&#x002F;truong-bit-trong-c-6650.html">
<meta name="author" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :.">
<meta name="copyright" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :. [admin@nguoicodonvn2008.info]">
<meta name="robots" content="index, archive, follow, noodp">
<meta name="googlebot" content="index,archive,follow,noodp">
<meta name="msnbot" content="all,index,follow">
<meta name="generator" content="NukeViet v4.5">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta property="og:title" content="Trường Bit trong C">
<meta property="og:type" content="website">
<meta property="og:description" content="Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;www.nguoicodonvn2008.info&#x002F;vi&#x002F;news&#x002F;savefile&#x002F;kien-thuc-may-tinh&#x002F;truong-bit-trong-c-6650.html">
<meta property="og:site_name" content=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.">
<meta property="og:url" content="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/truong-bit-trong-c-6650.html">
<link rel="shortcut icon" href="https://www.nguoicodonvn2008.info/favicon.ico">
<link rel="canonical" href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/truong-bit-trong-c-6650.html">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/" title="Tin Tức" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/karaoke-dual/" title="Tin Tức - Karaoke Dual" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/nhac-tre/" title="Tin Tức - Nhạc trẻ" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tru-tinh/" title="Tin Tức - Trữ tình" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/nuoc-ngoai/" title="Tin Tức - Nước ngoài" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/remix/" title="Tin Tức - Remix" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tam-su-tinh-yeu/" title="Tin Tức - Tâm sự tình yêu" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tho-suu-tam/" title="Tin Tức - Thơ sưu tầm" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/cuoc-song/" title="Tin Tức - Cuộc sống" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/phan-mem/" title="Tin Tức - Phần mềm" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/kien-thuc-may-tinh/" title="Tin Tức - Kiến thức máy tính" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/hoc-tap/" title="Tin Tức - Học tập" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tai-lieu/" title="Tin Tức - Tài liệu" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/de-thi/" title="Tin Tức - Đề thi" type="application/rss+xml">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/assets/css/font-awesome.min.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/style.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/style.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/news.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/custom.css" type="text/css">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/jquery/jquery.min.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/language/vi.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/global.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/site.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/news.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/main.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/custom.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/bootstrap.min.js" type="text/javascript">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/style.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/style.non-responsive.css">
<link rel="StyleSheet" href="https://www.nguoicodonvn2008.info/themes/default/css/news.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/custom.css">
<style type="text/css">
	body{background: #fff;}
</style>
    </head>
    <body>
<div id="print">
	<div id="hd_print">
		<h2 class="pull-left">.&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.</h2>
		<p class="pull-right"><a title=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;." href="https://www.nguoicodonvn2008.info/">https://www.nguoicodonvn2008.info</a></p>
	</div>
	<div class="clear"></div>
	<hr />
	<div id="content">
		<h1>Trường Bit trong C</h1>
		<ul class="list-inline">
			<li>Thứ ba - 31/01/2023 23:56</li>
			<li class="hidden-print txtrequired"><em class="fa fa-print">&nbsp;</em><a title="In ra" href="javascript:;" onclick="window.print()">In ra</a></li>
			<li class="hidden-print txtrequired"><em class="fa fa-power-off">&nbsp;</em><a title="Đóng cửa sổ này" href="javascript:;" onclick="window.close()">Đóng cửa sổ này</a></li>
		</ul>
		<div class="clear"></div>
		<div id="hometext">
		</div>
				<div class="imghome">
			<img alt="Trường Bit trong C" src="https://quantrimang.com/hoc/ham-fgets-trong-c-157905" width="460" class="img-thumbnail" />
		</div>
		<div class="clear"></div>
		<div id="bodytext" class="clearfix">
			<p style="text-align: justify;"><strong>Bit Field trong C</strong>&nbsp;là gì?&nbsp;<strong>Cách dùng Bit Field trong C&nbsp;</strong>như thế nào? Hãy cùng Quantrimang.com tìm hiểu nhé!</p>

<p style="text-align: justify;">Giả sử chương trình&nbsp;C&nbsp;của bạn bao gồm một số lượng biến TRUE/FALSE được nhóm trong một cấu trúc gọi là&nbsp;<strong>trangthai</strong>&nbsp;để kiểm tra xem hàng hóa sản xuất ra có đủ chiều rộng, chiều cao cho phép không, như sau:</p>

<pre id="pre0" style="text-align: justify;">
struct
{
  unsigned int chieurong;
  unsigned int chieucao;
} trangthai;</pre>

<p style="text-align: justify;">Cấu trúc này yêu cầu 8 bytes bộ nhớ nhưng thực tế nó dự trữ 0 hoặc 1 byte mỗi biến. Ngôn ngữ lập trình C có một cách tối ưu bộ nhớ trong trường hợp này. Bạn đang sử dụng các biến bên trong cấu trúc sau đó bạn có thể định nghĩa độ lớn các biến, nó sẽ thông báo cho trình biên dịch C việc chỉ sử dụng số lượng byte này. Ví dụ, cấu trúc bên trên có thể được viết lại như sau:</p>

<pre id="pre1" style="text-align: justify;">
struct
{
  unsigned int chieurong : 1;
  unsigned int chieucao : 1;
} trangthai;</pre>

<p style="text-align: justify;">Bây giờ cấu trúc trên sẽ yêu cầu 4 byte cho bộ nhớ cho biến trangthai nhưng chỉ 2 bit được sử dụng để lưu trữ giá trị. Bạn phải sử dụng đến 32 biến với độ dài 1 bit này, do đó cấu trúc này sẽ sử dụng 4 byte và khi bạn có 33 biến, nó sẽ cấp phát ví trị tiếp theo trong bộ nhớ và bắt đầu sử dụng 8 byte. Bây giờ chúng ta hãy kiểm tra ví dụ dưới đây để hiểu về định nghĩa này.</p>

<pre id="pre2" style="text-align: justify;">
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

/* dinh nghia mot cau truc don gian */
struct
{
  unsigned int chieurong;
  unsigned int chieucao;
} trangthai1;

/* dinh nghia mot cau truc voi cac truong bit */
struct
{
  unsigned int chieurong : 1;
  unsigned int chieucao : 1;
} trangthai2;
int main( )
{
   printf( &quot;Bo nho bi chiem giu boi trangthai1 la: %d\n&quot;, sizeof(trangthai1));
   printf( &quot;Bo nho bi chiem giu boi trangthai2 la: %d\n&quot;, sizeof(trangthai2));
   printf(&quot;\n===========================\n&quot;);
   printf(&quot;QTM chuc cac ban hoc tot! \n&quot;);

   return 0;
}</pre>

<p style="text-align: justify;">Biên dịch và chạy chương trình C trên sẽ cho kết quả:</p>

<p style="text-align: justify;"><img alt="" data-i="0" data-src="https://st.quantrimang.com/photos/image/2018/08/03/truong-bit-trong-c-1.jpg" data-was-processed="true" height="87" src="https://st.quantrimang.com/photos/image/2018/08/03/truong-bit-trong-c-1.jpg" width="370" /></p>

<h2 style="text-align: justify;">Khai báo Trường Bit trong C</h2>

<p style="text-align: justify;">Khai báo một Trường Bit bên trong một cấu trúc có mẫu như sau:</p>

<pre id="pre3" style="text-align: justify;">
struct
{
  kieu_du_lieu &#91;ten_thanh_vien&#93; : do_rong ;
};</pre>

<p style="text-align: justify;">Dưới đây là mô tả cho các phần tử biến trong một Trường Bit:</p>

<table border="2" cellpadding="2">
	<tbody>
		<tr>
			<th style="text-align: justify;">Phần tử</th>
			<th style="text-align: justify;">Mô tả</th>
		</tr>
		<tr>
			<td style="text-align: justify;">kieu_du_lieu</td>
			<td style="text-align: justify;">Một kiểu integer có thể xác định cách Trường Bit được thông dịch. Kiểu này có thể là int, signed int, unsigned int</td>
		</tr>
		<tr>
			<td style="text-align: justify;">ten_thanh_vien</td>
			<td style="text-align: justify;">Tên của Trường Bit.</td>
		</tr>
		<tr>
			<td style="text-align: justify;">do_rong</td>
			<td style="text-align: justify;">(là độ rộng) Số lượng bit có trong một trường. Độ dài phải nhỏ hơn hoặc bằng độ dài Trường Bit của một đối tượng cụ thể.</td>
		</tr>
	</tbody>
</table>

<p style="text-align: justify;">Một biến được định nghĩa với giá trị độ lớn được cho sẵn được gọi là&nbsp;<strong>Trường Bit</strong>. Một Trường Bit có thể lưu trữ nhiều hơn một bit đơn ví dụ bạn cần một biến để lưu trữ các giá trị từ 0 đến 7, sau đó bạn có thể định nghĩa Trường Bit với độ dài tối đa là 3 bit như sau:</p>

<pre id="pre4" style="text-align: justify;">
struct
{
  unsigned int tuoi : 3;
} Tuoi;</pre>

<p style="text-align: justify;">Việc định nghĩa trên sẽ hướng dẫn trình biên dịch C là biến sẽ sử dụng 3 bit để dự trữ các giá trị, nếu bạn sử dụng nhiều hơn 3 bit nó sẽ không cho phép bạn làm thế. Bây giờ hãy thử ví dụ dưới đây:</p>

<pre id="pre5" style="text-align: justify;">
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

struct
{
  unsigned int tuoi : 3;
} Tuoi;

int main( )
{
   Tuoi.tuoi = 3;
   printf( &quot;Bo nho bi chiem giu boi Tuoi la Sizeof( Tuoi ) =  %d\n&quot;, sizeof(Tuoi) );
   printf( &quot;Tuoi.tuoi : %d\n&quot;, Tuoi.tuoi );

   Tuoi.tuoi = 6;
   printf( &quot;Tuoi.tuoi : %d\n&quot;, Tuoi.tuoi );

   Tuoi.tuoi = 7;
   printf( &quot;Tuoi.tuoi : %d\n&quot;, Tuoi.tuoi );
   /* Bay gio chung ta thu in nhieu hon 3 bit */
   printf( &quot;\n-----------------------\n&quot;);
   Tuoi.tuoi = 8;
   printf( &quot;Tuoi.tuoi : %d\n&quot;, Tuoi.tuoi );
   Tuoi.tuoi = 9;
   printf( &quot;Tuoi.tuoi : %d\n&quot;, Tuoi.tuoi );
   printf(&quot;\n===========================\n&quot;);
   printf(&quot;QTM chuc cac ban hoc tot! \n&quot;);

   return 0;
}</pre>

<p style="text-align: justify;">Biên dịch và chạy chương trình C trên sẽ cho kết quả:</p>

<p style="text-align: justify;"><img alt="" data-i="1" data-src="https://st.quantrimang.com/photos/image/2018/08/03/truong-bit-trong-c-2.jpg" data-was-processed="true" src="https://st.quantrimang.com/photos/image/2018/08/03/truong-bit-trong-c-2.jpg" /></p>

<h2 style="text-align: justify;">Những sự thật thú vị về bit field trong C</h2>

<p style="text-align: justify;">1. Một trường bit không tên đặc biệt của&nbsp;<strong>size 0</strong>&nbsp;được dùng để buộc căn chỉnh trên giới hạn tiếp theo. Ví dụ:</p>

<pre id="pre6" style="text-align: justify;">
#include &lt;stdio.h&gt;

// A structure without forced alignment
struct test1 {
	unsigned int x : 5;
	unsigned int y : 8;
};

// A structure with forced alignment
struct test2 {
	unsigned int x : 5;
	unsigned int : 0;
	unsigned int y : 8;
};

int main()
{
	printf(&quot;Size of test1 is %lu bytes\n&quot;,
		sizeof(struct test1));
	printf(&quot;Size of test2 is %lu bytes\n&quot;,
		sizeof(struct test2));
	return 0;
}
</pre>

<p style="text-align: justify;"><strong>Kết quả</strong></p>

<ul>
	<li style="text-align: justify;">Kích thước của test1 là 4 byte</li>
	<li style="text-align: justify;">Kích thước của test2 là 8 byte</li>
</ul>

<p style="text-align: justify;">2. Không thể có các con trỏ tới thành phần trường bit bởi chúng có thể không bắt đầu ở giới hạn byte. Ví dụ:</p>

<pre id="pre7" style="text-align: justify;">
#include &lt;stdio.h&gt;
struct test {
	unsigned int x : 5;
	unsigned int y : 5;
	unsigned int z;
};
int main()
{
	struct test t;

	// Uncommenting the following line will make
	// the program compile and run
	printf(&quot;Address of t.x is %p&quot;, &amp;t.x);

	// The below line works fine as z is not a
	// bit field member
	printf(&quot;Address of t.z is %p&quot;, &amp;t.z);
	return 0;
}
</pre>

<p style="text-align: justify;">Kết quả:</p>

<pre id="pre8" style="text-align: justify;">
prog.c: In function &#039;main&#039;:
prog.c:14:1: error: cannot take address of bit-field &#039;x&#039;
 printf(&quot;Address of t.x is %p&quot;, &amp;t.x); 
 ^</pre>
		</div>
				<div id="author">
						<p>
				<strong>Nguồn tin:</strong>
				Quantrimang.com
			</p>
		</div>
	</div>
	<div id="footer" class="clearfix">
		<div id="url">
			<strong>URL của bản tin này: </strong><a href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/truong-bit-trong-c-6650.html" title="Trường Bit trong C">https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/truong-bit-trong-c-6650.html</a>

		</div>
		<div class="clear"></div>
		<div class="copyright">
			&copy; .&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.
		</div>
		<div id="contact">
			<a href="mailto:admin@nguoicodonvn2008.info">admin@nguoicodonvn2008.info</a>
		</div>
	</div>
</div>
        <div id="timeoutsess" class="chromeframe">
            Bạn đã không sử dụng Site, <a onclick="timeoutsesscancel();" href="https://www.nguoicodonvn2008.info/#">Bấm vào đây để duy trì trạng thái đăng nhập</a>. Thời gian chờ: <span id="secField"> 60 </span> giây
        </div>
        <div id="openidResult" class="nv-alert" style="display:none"></div>
        <div id="openidBt" data-result="" data-redirect=""></div>
		</script>
		<div class="car-top">
  <span><img src="https://www.nguoicodonvn2008.info/themes/default/images/car.png" alt=""></span>
</div>
<div id="run_cronjobs" style="visibility:hidden;display:none;"><img alt="cron" src="/index.php?second=cronjobs&amp;p=i66jT3r1" width="1" height="1" /></div>
<script src="https://www.nguoicodonvn2008.info/assets/js/jquery/jquery.min.js"></script>
<script>var nv_base_siteurl="/",nv_lang_data="vi",nv_lang_interface="vi",nv_name_variable="nv",nv_fc_variable="op",nv_lang_variable="language",nv_module_name="news",nv_func_name="savefile",nv_is_user=0, nv_my_ofs=-4,nv_my_abbr="EDT",nv_cookie_prefix="nv4c_e856T",nv_check_pass_mstime=1738000,nv_area_admin=0,nv_safemode=0,theme_responsive=0,nv_recaptcha_ver=2,nv_recaptcha_sitekey="",nv_recaptcha_type="image",XSSsanitize=1;</script>
<script src="https://www.nguoicodonvn2008.info/assets/js/language/vi.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/global.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/site.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/news.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/main.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/custom.js"></script>
<script type="application/ld+json">
        {
            "@context": "https://schema.org",
            "@type": "Organization",
            "url": "https://www.nguoicodonvn2008.info",
            "logo": "https://www.nguoicodonvn2008.info/uploads/angel.gif"
        }
        </script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/bootstrap.min.js"></script>
<script type="text/javascript">
var $scrolltop = $('.car-top');
$scrolltop.on('click', function () {
    $('html,body').animate({
        scrollTop: 0
    }, 800);
    $(this).addClass("car-run");
    setTimeout(function(){ $scrolltop.removeClass('car-run');}, 1000);
    return false;
});
$(window).on('scroll', function ()
{ 
    if($(window).scrollTop() >= 200)
    {
        $scrolltop.addClass("show");
        $scrolltop.addClass("car-down");
    }
    else
    {
       $scrolltop.removeClass("show");
       setTimeout(function(){ $scrolltop.removeClass('car-down');}, 300);
    }
});
</script>
</body>
</html>