How to read bits from file or extract bits from Byte? (1 bit Boolean, variable-bits Integer?)

87 views
Skip to first unread message

Nikolay Tsutsarin

unread,
Jul 13, 2017, 1:07:06 AM7/13/17
to Haxe
For example. I have a binary file with following written into it:
- 1 bit (Boolean)
- 1 bit (Boolean)
- 2 bit (Integer)
- 12 bit (Integer)
In parens are types which I want to read from this file.

Hugh

unread,
Jul 13, 2017, 1:44:51 AM7/13/17
to Haxe
You can only read whole bytes from a file.
So it depends how the bits are laid-out.  Looks like you have a 16-bit number so it could be stored as 2 bytes.
If you are using the haxe.io.Input api, it might look like this:



// Assume little-endian - low first...
var low = input.readByte();
var high = input.readByte(); 

The it might be:

var bool0 = ( high & 0x80 ) > 0;
var bool1 = ( high & 0x40 ) > 0; 
var miniInt = ( high & 0x30 ) >> 4;
var int12 = ((high & 0x0f) << 8 ) | low;

But it really depends on how the bits are on the file.

Nikolay Tsutsarin

unread,
Jul 13, 2017, 1:54:19 AM7/13/17
to Haxe
Wow, awesome, so fast reply!
I have big endian encoding according to documentation, so how I have to change the code?
Also, I know almost nothing about system and low-level programming, where I can read theory primary on working with bits, bytes, endians and so on?

Juraj Kirchheim

unread,
Jul 13, 2017, 2:58:50 AM7/13/17
to haxe...@googlegroups.com
Swap the two first lines of code:

// Assume big-endian - high first...
var high = input.readByte(); 
var low = input.readByte();

Best,
Juraj

--
To post to this group haxe...@googlegroups.com
http://groups.google.com/group/haxelang?hl=en
---
You received this message because you are subscribed to the Google Groups "Haxe" group.
For more options, visit https://groups.google.com/d/optout.

Nikolay Tsutsarin

unread,
Jul 13, 2017, 3:31:47 PM7/13/17
to haxe...@googlegroups.com
Everything works, thank you!

You received this message because you are subscribed to a topic in the Google Groups "Haxe" group.
Reply all
Reply to author
Forward
0 new messages