473,386 Members | 1,773 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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

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
Feb 16 '06 #1
7 14126
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?
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Doru Roman" <do*******@rogers.com> wrote in message
news:Od*************@tk2msftngp13.phx.gbl...
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

Feb 16 '06 #2
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.
--
HTH
Stoitcho Goutsev (100)

"Doru Roman" <do*******@rogers.com> wrote in message
news:Od*************@tk2msftngp13.phx.gbl...
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

Feb 16 '06 #3
"Doru Roman" <do*******@rogers.com> wrote in message news:Od*************@tk2msftngp13.phx.gbl...
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
Feb 17 '06 #4
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.
Feb 17 '06 #5
Doru Roman wrote:
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.Win dows.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.Wind ows.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.currentTextBoxChangedEven tHander);
this.hexText.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.HexTextK eyDown);
//
// 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.Wind ows.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.currentTextBoxChangedEven tHander);
this.decText.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.DecTextK eyDown);
//
// 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.Wind ows.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.currentTextBoxChangedEven tHander);
this.octText.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.OctTextK eyDown);
//
// 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.Wind ows.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.currentTextBoxChangedEven tHander);
this.binText.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.BinTextK eyDown);
//
// 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[i]==current) continue;

TextBox t = texts[i];
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.");
}

}
}
}
Feb 17 '06 #6
Doru Roman wrote:
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.
--
Derrick Coetzee, MCAD, MSFT (Speech Server)
This posting is provided "AS IS" with no warranties, and confers no
rights.
Feb 17 '06 #7
Derrick Coetzee [MSFT] wrote:
Doru Roman wrote:
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.


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.
--
Derrick Coetzee, MCAD, MSFT (Speech Server)
This posting is provided "AS IS" with no warranties, and confers no
rights.
Feb 17 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: DraguVaso | last post by:
Hi, I need to find the FASTEST way to get a string in a Loop, that goes from "a" to "ZZZZZZZZZZZZZZZZZ". So it has to go like this: a b .... z
4
by: laurenq uantrell | last post by:
I am trying to determine which of three stored procedure designs are fastest in the Query Analyzer: One query is a straight SELECT query with all desired rows and a dozen (tblName.RowName =...
11
by: hoopsho | last post by:
Hi Everyone, I am trying to write a program that does a few things very fast and with efficient use of memory... a) I need to parse a space-delimited file that is really large, upwards fo a...
24
by: ThunderMusic | last post by:
Hi, The subject says it all... I want to use a byte and use it as byte* so I can increment the pointer to iterate through it. What is the fastest way of doing so in C#? Thanks ThunderMusic
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.