Recent

Author Topic: Working with bits  (Read 4351 times)

xinyiman

  • Hero Member
  • *****
  • Posts: 2261
    • Lazarus and Free Pascal italian community
Working with bits
« on: July 20, 2011, 08:33:38 am »
Hello guys, I was wondering how you can recover in lazarus bits that make up a character. So as to see them in the form of 1 and 0.

thanks Hello
Win10, Ubuntu and Mac
Lazarus: 2.1.0
FPC: 3.3.1

Zoran

  • Hero Member
  • *****
  • Posts: 1988
    • http://wiki.lazarus.freepascal.org/User:Zoran
Re: Working with bits
« Reply #1 on: July 20, 2011, 09:44:40 am »
Start new project, add these functions:
Code: [Select]
function ByteToBits(B: Byte): String;
var
  I: Integer;
  N: Byte;
begin
  Result := '';
  for I := 1 to 8 do begin
    Result := IntToStr(B and 1) + Result;
    B := B shr 1;
  end;
end;

function CharToBits(C: Char): String;
begin
  Result := ByteToBits(Byte(C));
end;

Now, put three items on the form: Edit, ListBox and Button.

To test it, put this in button's OnClick event:
Code: [Select]
{ This first character in Edit box is converted to its binary presentation }
procedure TForm1.Button1Click(Sender: TObject);
begin
  if Length(Edit1.Text) > 0 then
    ListBox1.AddItem(CharToBits(Edit1.Text[1]), nil)
  else begin
    MessageDlg('Type something in edit box!', mtError, [mbOk], 0);
    Edit1.SetFocus;
  end;
end;

Note: If the character in edit box needs more than one byte in utf8 presentation (that is, if it is non-latin or accented character), then only the first byte will be shown.
« Last Edit: July 20, 2011, 09:47:36 am by Zoran »
Swan, ZX Spectrum emulator https://github.com/zoran-vucenovic/swan

xinyiman

  • Hero Member
  • *****
  • Posts: 2261
    • Lazarus and Free Pascal italian community
Re: Working with bits
« Reply #2 on: July 20, 2011, 01:41:20 pm »
Thank you
Win10, Ubuntu and Mac
Lazarus: 2.1.0
FPC: 3.3.1

BigChimp

  • Hero Member
  • *****
  • Posts: 5740
  • Add to the wiki - it's free ;)
    • FPCUp, PaperTiger scanning and other open source projects
Re: Working with bits
« Reply #3 on: July 20, 2011, 02:46:31 pm »
Also, have a search through the forum; there was a huge thread about doing bit-level manipulation, including different ways of doing that..
Want quicker answers to your questions? Read http://wiki.lazarus.freepascal.org/Lazarus_Faq#What_is_the_correct_way_to_ask_questions_in_the_forum.3F

Open source including papertiger OCR/PDF scanning:
https://bitbucket.org/reiniero

Lazarus trunk+FPC trunk x86, Windows x64 unless otherwise specified

 

TinyPortal © 2005-2018