Version française
Home     About     Download     Resources     Contact us    
Browse thread
How can I treat bits?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Xavier Leroy <Xavier.Leroy@i...>
Subject: Re: How can I treat bits?
> In C language, we can define a variable size as a unit of bits.
> For example,  "unsigned int a:1 ;", " unsigned int b:4 ;" ....
> "colon" is used to set up the number of bits.
> 
> Can I define OCaml-variables in the same way?

No, you can't.  The smallest unit for data representations is the
machine word.  You can also work at the level of bytes by using
strings as byte arrays.

> Because I want to make some data header by using bits as little as
> possible. 
> the style that I imagine is... 
> 	type hd = { flag : int_1 ; on_off : int_1 ; seq_num : int_4 } ;;
> 	let header = { flag = 1 ; on_off = 0 ; seq_num = 0101 } ;;

The best you could do is represent hd as an integer and define
constructor and accessors yourself:

        type hd = int
        let make_hd flag on_off seq_num =
          flag lor (on_off lsl 1) lor (seq_num lsl 2)
        let flag_hd h = h land 1
        let on_off_hd h = (h lsr 1) land 1
        let seq_num_hd h = (h lsr 2) land 0xF

- Xavier Leroy