The fastest way to determine c = (byte)a & b

D

Doru Roman

Hi,

What is the fastest way to evaluate manually the result in this case:

int a, b, c;
a = 255;
b = 122;
c = a & b;

The only way I know is transforming each number into the binary value and
then applying the & operator, then the result changed back into a decimal:
122.
Is there another faster way to determine it?

Thanks,
Doru
 
N

Nicholas Paldino [.NET/C# MVP]

Doru,

If your mask (a) is always 255, then you could do this:

int c = (b << 4) >> 4;

But I don't know if that is faster or not. I would think it isn't.

Is there a reason the standard binary and operator doesn't suit your
needs?
 
S

Stoitcho Goutsev \(100\)

Doru,

If you have in mind exactly this numbers 122 and 255 then the result is 122
:)

If one of the operands is always 255 then the result of this operation is
the remainder after deviding by 256 (mod 256 or c#'s % operator)

Otherwise in the generic case with bitwise AND operation there is no exact
arithmetic equivalent.
 
B

Bill Butler

Doru Roman said:
Hi,

What is the fastest way to evaluate manually the result in this case:

int a, b, c;
a = 255;
b = 122;
c = a & b;

The only way I know is transforming each number into the binary value and then applying the &
operator, then the result changed back into a decimal: 122.
Is there another faster way to determine it?


I am Soooooo Confused
what is wrong with:

int a = 255;
int b = 122;
int c = a & b;
Console.WriteLine ("a:{0} b:{1} c:{2}", a, b, c);

produces: a:255 b:122 c:122

Perhaps I just missed the point of your post

Bill
 
D

Doru Roman

Thank you all for the reply.
What I was looking for was a fast MANUAL solution (not C#) to determine a &
b result when let's say none of the integers are 255.
 
S

Scott C

Doru said:
Thank you all for the reply.
What I was looking for was a fast MANUAL solution (not C#) to determine a &
b result when let's say none of the integers are 255.


I had a few <ahem> minutes, and I did this, as just a little exercise
and I thought you might like it.

It's a win form application with four text boxes (one for each base: 2,
8, 10, 12). Type into any to get the results in the others.

I apologize in advance for the line wrapping. If you really want it
nicely formatted, email me and i'll send it to you as an attachement.

Scott.

Quick and dirty, a single class:

---------------------------------------------
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;
using System.Text;

namespace NumberViewer
{
/// <summary>
/// Description of MainForm.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms
designer support.
//
InitializeComponent();

texts = new TextBox[] {
binText, octText, decText, hexText};
}

[STAThread]
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}

#region Windows Forms Designer generated code
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor.
The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent()
{
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.hexText = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.decText = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.octText = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.binText = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// groupBox2
//
this.groupBox2.Anchor =
((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox2.Controls.Add(this.hexText);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.decText);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Controls.Add(this.octText);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.binText);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Location = new System.Drawing.Point(1, 3);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(386, 136);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Type in any box";
this.groupBox2.UseCompatibleTextRendering = true;
//
// hexText
//
this.hexText.Anchor =
((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.hexText.Location = new System.Drawing.Point(71, 106);
this.hexText.Name = "hexText";
this.hexText.Size = new System.Drawing.Size(305, 21);
this.hexText.TabIndex = 7;
this.hexText.Tag = "16";
this.hexText.Enter += new
System.EventHandler(this.currentTextBoxChangedEventHander);
this.hexText.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.HexTextKeyDown);
//
// label4
//
this.label4.Location = new System.Drawing.Point(10, 106);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(100, 23);
this.label4.TabIndex = 6;
this.label4.Text = "Hex";
this.label4.UseCompatibleTextRendering = true;
//
// decText
//
this.decText.Anchor =
((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.decText.Location = new System.Drawing.Point(71, 76);
this.decText.Name = "decText";
this.decText.Size = new System.Drawing.Size(305, 21);
this.decText.TabIndex = 5;
this.decText.Tag = "10";
this.decText.Enter += new
System.EventHandler(this.currentTextBoxChangedEventHander);
this.decText.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.DecTextKeyDown);
//
// label3
//
this.label3.Location = new System.Drawing.Point(10, 76);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(100, 23);
this.label3.TabIndex = 4;
this.label3.Text = "Decimal";
this.label3.UseCompatibleTextRendering = true;
//
// octText
//
this.octText.Anchor =
((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.octText.Location = new System.Drawing.Point(71, 46);
this.octText.Name = "octText";
this.octText.Size = new System.Drawing.Size(305, 21);
this.octText.TabIndex = 3;
this.octText.Tag = "8";
this.octText.Enter += new
System.EventHandler(this.currentTextBoxChangedEventHander);
this.octText.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.OctTextKeyDown);
//
// label2
//
this.label2.Location = new System.Drawing.Point(10, 46);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(100, 23);
this.label2.TabIndex = 2;
this.label2.Text = "Octal";
this.label2.UseCompatibleTextRendering = true;
//
// binText
//
this.binText.Anchor =
((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.binText.Location = new System.Drawing.Point(72, 17);
this.binText.Name = "binText";
this.binText.Size = new System.Drawing.Size(305, 21);
this.binText.TabIndex = 1;
this.binText.Tag = "2";
this.binText.Enter += new
System.EventHandler(this.currentTextBoxChangedEventHander);
this.binText.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.BinTextKeyDown);
//
// label1
//
this.label1.Location = new System.Drawing.Point(11, 17);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Binary";
this.label1.UseCompatibleTextRendering = true;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(390, 142);
this.Controls.Add(this.groupBox2);
this.Name = "MainForm";
this.Text = "Number viewer";
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
private System.Windows.Forms.TextBox binText;
private System.Windows.Forms.TextBox hexText;
private System.Windows.Forms.TextBox decText;
private System.Windows.Forms.TextBox octText;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.GroupBox groupBox2;
#endregion

TextBox current;
TextBox[] texts;
EventHandler textChangedEvent;
long theNumber;

string getHexString() {
string s = Convert.ToString(theNumber, 16).ToUpper();

StringBuilder sb = new StringBuilder(s);
for(int i=s.Length; i>0; i-=2)
sb.Insert(i, " ");

return sb.ToString();
}
string getDecString() {
StringBuilder sb = new StringBuilder( Convert.ToString(theNumber, 10));
for(int i=sb.Length; i>0; i-=3)
sb.Insert(i, " ");

return sb.ToString();
}
string getBinString() {
StringBuilder sb =
new StringBuilder(Convert.ToString(theNumber, 2));

for(int i=sb.Length; i>0; i-=4)
sb.Insert(i, " ");
return sb.ToString();
}
string getOctString() {
return Convert.ToString(theNumber, 8);
}

// the "input" text box has changed
// user is typing in a different textbox
private void currentTextBoxChangedEventHander(object sender, EventArgs e)
{
// unwire event
if(current != null && textChangedEvent != null)
current.TextChanged -= textChangedEvent;

// change textbox and wire up
current = (TextBox)sender;
textChangedEvent = new EventHandler(this.textChangedEventHandler);
current.TextChanged += textChangedEvent;

}
// text in current textbox has changed, so update others
private void textChangedEventHandler(object sender, EventArgs e) {


try {
if( (sender as TextBox).TextLength==0)
theNumber = 0;
else
setTheNumber();

setTexts();
}
catch(FormatException ex) {
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
catch(ArgumentException ex) {
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
catch(OverflowException ex) {
MessageBox.Show(ex.Message, ex.GetType().ToString());
}

}
void setTexts() {
for(int i=0; i<texts.Length; i++) {
if(texts==current) continue;

TextBox t = texts;
int radix = Convert.ToInt32( t.Tag );
switch(radix) {
case 2: t.Text = getBinString(); break;
case 8: t.Text = getOctString(); break;
case 10:t.Text = getDecString(); break;
case 16:t.Text = getHexString(); break;
default: throw new ArgumentOutOfRangeException(
"Base must be one of 2, 8, 10 or 16.");
}
}
}
void setTheNumber() {
int radix = Convert.ToInt32(current.Tag);
string txt = current.Text.Replace(" ", "");
theNumber = Convert.ToInt32(current.Text, radix);
}

void BinTextKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
e.SuppressKeyPress = !keyIsValid(e.KeyCode, 2);
}

void OctTextKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
e.SuppressKeyPress = !keyIsValid(e.KeyCode, 8);
}

void DecTextKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
e.SuppressKeyPress = !keyIsValid(e.KeyCode, 10);
}

void HexTextKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
e.SuppressKeyPress = !keyIsValid(e.KeyCode, 16);
}
bool keyIsValid(Keys key, int radix) {
// non-printing characters
if(key == Keys.Back
|| key == Keys.Left || key == Keys.Right) {
return true;
}

int k = (int)key;
int low1, hi1; // numbers on top of keyboard
int low2, hi2; // numeric keypad
low1 = (int)Keys.D0;
low2 = (int)Keys.NumPad0;
switch(radix) {
case 2:
hi1 = (int)Keys.D1;
hi2 = (int)Keys.NumPad1;
return (low1 <= k && k <= hi1) || (low2 <= k && k <= hi2);

case 8:
hi1 = (int)Keys.D7;
hi2 = (int)Keys.NumPad7;
return (low1 <= k && k <= hi1) || (low2 <= k && k <= hi2);

case 10:
hi1 = (int)Keys.D9;
hi2 = (int)Keys.NumPad9;
return (low1 <= k && k <= hi1) || (low2 <= k && k <= hi2);

case 16:
// check for numeric value
if( ((int)Keys.D0 <= k && k <= (int)Keys.D9) ||
((int)Keys.NumPad0 <= k && k <= (int)Keys.NumPad9))
return true;
// check for a-f/A-F value
if( ((int)Keys.A <= k && k <= (int)Keys.F ))
return true;
return false;

default:
throw new ArgumentException("Invalid radix.");
}

}
}
}
 
D

Derrick Coetzee [MSFT]

Doru said:
Thank you all for the reply.
What I was looking for was a fast MANUAL solution (not C#) to
determine a & b result when let's say none of the integers are 255.

This is somewhat off-topic, but I think what you're actually looking for is
a way of computing binary AND directly on decimal numbers by hand (on
paper). In short, I can't think of any great way to do this. You can speed
up the binary conversion process quite a bit by memorizing the binary for 0
through 15 (or making a table of these), and then converting via
hexadecimal. For example:

152 divided by 16 = 9 remainder 8, so 152 = 0x98
9 = 1001b, 8 = 1000b
152 = 10011000b

Similarly, to convert back, just split the word in two and do one
multiplication by 16 and an add.

1101 0011 = 0xD3
13*16 + 3 = 211

Hope this helps.
 
D

Derrick Coetzee [MSFT]

Derrick said:
You can speed up the binary conversion process quite a bit by
memorizing the binary for 0 through 15 (or making a table of these),
and then converting via hexadecimal.

I forgot to mention: you can also use a table of multiples of 16 to speed up
multiplication and division by 16:

0 0
1 16
2 32
3 48
4 64
5 80
6 96
7 112
8 128
9 144
10 160
11 176
12 192
13 208
14 224
15 240

To multiply by 16, just find the number on the left and look at the number
on the right. To divide by 16, find the largest number on the right which is
no larger than your number - the quotient will be to its left and you can
subtract to get the remainder. For example, 185 divided by 16 is 11
remainder 9, because 185 is between 176 and 192, 11 is to the left of 176,
and 185-176 = 9. With these tricks you should be able to quickly convert
bytes to and from binary by hand.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top