473,756 Members | 1,881 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 14145
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.co m

"Doru Roman" <do*******@roge rs.com> wrote in message
news:Od******** *****@tk2msftng p13.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*******@roge rs.com> wrote in message
news:Od******** *****@tk2msftng p13.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*******@roge rs.com> wrote in message news:Od******** *****@tk2msftng p13.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.WriteLi ne ("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.Collecti ons.Generic;
using System.Drawing;
using System.Windows. Forms;
using System.Globaliz ation;
using System.Text;

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

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

[STAThread]
public static void Main(string[] args)
{
Application.Ena bleVisualStyles ();
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 InitializeCompo nent()
{
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.SuspendLay out();
//
// groupBox2
//
this.groupBox2. Anchor =
((System.Window s.Forms.AnchorS tyles)((((Syste m.Windows.Forms .AnchorStyles.T op
| System.Windows. Forms.AnchorSty les.Bottom)
| System.Windows. Forms.AnchorSty les.Left)
| System.Windows. Forms.AnchorSty les.Right)));
this.groupBox2. Controls.Add(th is.hexText);
this.groupBox2. Controls.Add(th is.label4);
this.groupBox2. Controls.Add(th is.decText);
this.groupBox2. Controls.Add(th is.label3);
this.groupBox2. Controls.Add(th is.octText);
this.groupBox2. Controls.Add(th is.label2);
this.groupBox2. Controls.Add(th is.binText);
this.groupBox2. Controls.Add(th is.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. UseCompatibleTe xtRendering = true;
//
// hexText
//
this.hexText.An chor =
((System.Window s.Forms.AnchorS tyles)(((System .Windows.Forms. AnchorStyles.To p
| System.Windows. Forms.AnchorSty les.Left)
| System.Windows. Forms.AnchorSty les.Right)));
this.hexText.Lo cation = new System.Drawing. Point(71, 106);
this.hexText.Na me = "hexText";
this.hexText.Si ze = new System.Drawing. Size(305, 21);
this.hexText.Ta bIndex = 7;
this.hexText.Ta g = "16";
this.hexText.En ter += new
System.EventHan dler(this.curre ntTextBoxChange dEventHander);
this.hexText.Ke yDown += new
System.Windows. Forms.KeyEventH andler(this.Hex TextKeyDown);
//
// label4
//
this.label4.Loc ation = new System.Drawing. Point(10, 106);
this.label4.Nam e = "label4";
this.label4.Siz e = new System.Drawing. Size(100, 23);
this.label4.Tab Index = 6;
this.label4.Tex t = "Hex";
this.label4.Use CompatibleTextR endering = true;
//
// decText
//
this.decText.An chor =
((System.Window s.Forms.AnchorS tyles)(((System .Windows.Forms. AnchorStyles.To p
| System.Windows. Forms.AnchorSty les.Left)
| System.Windows. Forms.AnchorSty les.Right)));
this.decText.Lo cation = new System.Drawing. Point(71, 76);
this.decText.Na me = "decText";
this.decText.Si ze = new System.Drawing. Size(305, 21);
this.decText.Ta bIndex = 5;
this.decText.Ta g = "10";
this.decText.En ter += new
System.EventHan dler(this.curre ntTextBoxChange dEventHander);
this.decText.Ke yDown += new
System.Windows. Forms.KeyEventH andler(this.Dec TextKeyDown);
//
// label3
//
this.label3.Loc ation = new System.Drawing. Point(10, 76);
this.label3.Nam e = "label3";
this.label3.Siz e = new System.Drawing. Size(100, 23);
this.label3.Tab Index = 4;
this.label3.Tex t = "Decimal";
this.label3.Use CompatibleTextR endering = true;
//
// octText
//
this.octText.An chor =
((System.Window s.Forms.AnchorS tyles)(((System .Windows.Forms. AnchorStyles.To p
| System.Windows. Forms.AnchorSty les.Left)
| System.Windows. Forms.AnchorSty les.Right)));
this.octText.Lo cation = new System.Drawing. Point(71, 46);
this.octText.Na me = "octText";
this.octText.Si ze = new System.Drawing. Size(305, 21);
this.octText.Ta bIndex = 3;
this.octText.Ta g = "8";
this.octText.En ter += new
System.EventHan dler(this.curre ntTextBoxChange dEventHander);
this.octText.Ke yDown += new
System.Windows. Forms.KeyEventH andler(this.Oct TextKeyDown);
//
// label2
//
this.label2.Loc ation = new System.Drawing. Point(10, 46);
this.label2.Nam e = "label2";
this.label2.Siz e = new System.Drawing. Size(100, 23);
this.label2.Tab Index = 2;
this.label2.Tex t = "Octal";
this.label2.Use CompatibleTextR endering = true;
//
// binText
//
this.binText.An chor =
((System.Window s.Forms.AnchorS tyles)(((System .Windows.Forms. AnchorStyles.To p
| System.Windows. Forms.AnchorSty les.Left)
| System.Windows. Forms.AnchorSty les.Right)));
this.binText.Lo cation = new System.Drawing. Point(72, 17);
this.binText.Na me = "binText";
this.binText.Si ze = new System.Drawing. Size(305, 21);
this.binText.Ta bIndex = 1;
this.binText.Ta g = "2";
this.binText.En ter += new
System.EventHan dler(this.curre ntTextBoxChange dEventHander);
this.binText.Ke yDown += new
System.Windows. Forms.KeyEventH andler(this.Bin TextKeyDown);
//
// label1
//
this.label1.Loc ation = new System.Drawing. Point(11, 17);
this.label1.Nam e = "label1";
this.label1.Siz e = new System.Drawing. Size(100, 23);
this.label1.Tab Index = 0;
this.label1.Tex t = "Binary";
this.label1.Use CompatibleTextR endering = true;
//
// MainForm
//
this.AutoScaleD imensions = new System.Drawing. SizeF(6F, 13F);
this.AutoScaleM ode = System.Windows. Forms.AutoScale Mode.Font;
this.ClientSize = new System.Drawing. Size(390, 142);
this.Controls.A dd(this.groupBo x2);
this.Name = "MainForm";
this.Text = "Number viewer";
this.groupBox2. ResumeLayout(fa lse);
this.groupBox2. PerformLayout() ;
this.ResumeLayo ut(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 textChangedEven t;
long theNumber;

string getHexString() {
string s = Convert.ToStrin g(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.ToStrin g(theNumber, 10));
for(int i=sb.Length; i>0; i-=3)
sb.Insert(i, " ");

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

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

// the "input" text box has changed
// user is typing in a different textbox
private void currentTextBoxC hangedEventHand er(object sender, EventArgs e)
{
// unwire event
if(current != null && textChangedEven t != null)
current.TextCha nged -= textChangedEven t;

// change textbox and wire up
current = (TextBox)sender ;
textChangedEven t = new EventHandler(th is.textChangedE ventHandler);
current.TextCha nged += textChangedEven t;

}
// text in current textbox has changed, so update others
private void textChangedEven tHandler(object sender, EventArgs e) {
try {
if( (sender as TextBox).TextLe ngth==0)
theNumber = 0;
else
setTheNumber();

setTexts();
}
catch(FormatExc eption ex) {
MessageBox.Show (ex.Message, ex.GetType().To String());
}
catch(ArgumentE xception ex) {
MessageBox.Show (ex.Message, ex.GetType().To String());
}
catch(OverflowE xception ex) {
MessageBox.Show (ex.Message, ex.GetType().To String());
}

}
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 ArgumentOutOfRa ngeException(
"Base must be one of 2, 8, 10 or 16.");
}
}
}
void setTheNumber() {
int radix = Convert.ToInt32 (current.Tag);
string txt = current.Text.Re place(" ", "");
theNumber = Convert.ToInt32 (current.Text, radix);
}

void BinTextKeyDown( object sender, System.Windows. Forms.KeyEventA rgs e)
{
e.SuppressKeyPr ess = !keyIsValid(e.K eyCode, 2);
}

void OctTextKeyDown( object sender, System.Windows. Forms.KeyEventA rgs e)
{
e.SuppressKeyPr ess = !keyIsValid(e.K eyCode, 8);
}

void DecTextKeyDown( object sender, System.Windows. Forms.KeyEventA rgs e)
{
e.SuppressKeyPr ess = !keyIsValid(e.K eyCode, 10);
}

void HexTextKeyDown( object sender, System.Windows. Forms.KeyEventA rgs e)
{
e.SuppressKeyPr ess = !keyIsValid(e.K eyCode, 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.NumPa d0;
switch(radix) {
case 2:
hi1 = (int)Keys.D1;
hi2 = (int)Keys.NumPa d1;
return (low1 <= k && k <= hi1) || (low2 <= k && k <= hi2);

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

case 10:
hi1 = (int)Keys.D9;
hi2 = (int)Keys.NumPa d9;
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.NumP ad0 <= k && k <= (int)Keys.NumPa d9))
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 ArgumentExcepti on("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
2325
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
3560
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 = @param or @param = Null) filters in the WHERE statement. One query populates a #Temp table with the UniqueIDs from the results of the SELECT query in the above example, then joins that #Temp table to get the desired rows.
11
3618
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 million lines. b) I need to store the contents into a unique hash. c) I need to then sort the data on a specific field. d) I need to pull out certain fields and report them to the user.
24
2292
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
9287
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10046
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9886
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9857
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9722
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6542
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3369
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2677
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.