#### Determine the number of bits in a negative number

```I'd like to determine the number of bits (the position
of the highest on bit) in a negative number (say -1)
without using knowledge of its type.

Valid operations would be AND, OR, XOR, negation,
and one's compliment can be done as:

'Get a -1 of the same type as myvar
Dim minus1: minus1 = myvar - (myvar + 1)
Dim onesComp: onesComp = myvar XOR minus1

You could also use multiplication or division by 2
or other mathematical operators/functions, but
then sign extension comes into play.

The standard solution is to presume the answer
given the type of the variable, but that is not very
generic.

Csaba Gabor from Vienna

By the way, this is equivalent to the problem of
determining the number of bits (both on and off
bits) in a given variable.
```
 0
Csaba
12/2/2009 9:18:16 AM
scripting.vbscript 564 articles. 0 followers.

8 Replies
964 Views

Similar Articles

[PageSpeed] 7

```Csaba Gabor wrote:
> I'd like to determine the number of bits (the position
> of the highest on bit) in a negative number (say -1)
> without using knowledge of its type.
>

The "brute force" way would be to "shift left" one bit
at a time, until you hit your 1-bit.

Problem is, you can't shift left in script.  There are
a number of shifting functions written in VB, but they
require calling the system api.

Most scripters abhor calling the system api, and so
your best bet is to wait around for a more knowledgable
person to come along with a "pure script" solution.

cheers, jw
```
 0
mr_unreliable
12/2/2009 5:46:39 PM
```mr_unreliable wrote:
> Problem is, you can't shift left in script.  There are
> a number of shifting functions written in VB, but they
> require calling the system api.
>

Maybe not.  See here:

http://www.freevbcode.com/ShowCode.asp?ID=2045

or here:

http://www.bitwisemag.com/2/Bit-Shifting-in-Visual-Basic-6

I spoke too soon.

mea culpa, jw
```
 0
mr_unreliable
12/2/2009 6:07:58 PM
```On Dec 2, 12:46=A0pm, mr_unreliable <kindlyReplyToNewsgr...@notmail.com>
wrote:
> Csaba Gabor wrote:
> > I'd like to determine the number of bits (the position
> > of the highest on bit) in a negative number (say -1)
> > without using knowledge of its type.
>
> The "brute force" way would be to "shift left" one bit
> at a time, until you hit your 1-bit.
>
> Problem is, you can't shift left in script. =A0There are
> a number of shifting functions written in VB, but they
> require calling the system api.
>
> Most scripters abhor calling the system api, and so
> your best bet is to wait around for a more knowledgable
> person to come along with a "pure script" solution.
>
> cheers, jw

JScript has SHIFT operators, so the old trick of using JScript in VBS
will work ...

wsh.echo ShiftRight(clng(-1) and &h7fffffff&, 30)

Function ShiftRight(arg, n)
with createobject("htmlfile")
.write "<script>var a=3D" & arg & ">>" & n & ";</script>"
ShiftRight =3D .parentWindow.a
end with
end function

Function ShiftLeft(arg, n)
with createobject("htmlfile")
.write "<script>var a=3D" & arg & "<<" & n & ";</script>"
ShiftLeft =3D .parentWindow.a
end with
end function

I also propose ANDing the number (converted to a Long - 32 bit -
number) with a mask that zeros the minus sign bit.  Then the other
bits can be tested.  The shift that first returns a value of zero is
the most significant bit (I didn't bother to show the test loop).

BTW, your shift nomenclature seems backward to me.  I guess you were
thinking of shifting the mask and not the number.  However, starting
from the MSB end would still seem most efficient and would still shift
the mask to the right, not the left wouldn't it?
_____________________
Tom Lavedas
```
 0
Tom
12/2/2009 6:27:26 PM
```Tom Lavedas wrote:
> BTW, your shift nomenclature seems backward to me.  I guess you were
> thinking of shifting the mask and not the number.  However, starting
> from the MSB end would still seem most efficient and would still shift
> the mask to the right, not the left wouldn't it?
>

I wasn't clear in expressing what I was thinking --
which was to put a MASK in the left-most bit, then
shifting the DATA left one bit at a time, masking
to see what the left-most bit was, and then counting
the number of zero's, until a 1-bit was reached.

But then, my verbal skills have always been lacking,
even worse than GWB!

Regardless, as jscript has a shift function, that
sounds like the way to go.

cheers, jw
```
 0
mr_unreliable
12/2/2009 8:46:45 PM
```"mr_unreliable" <kindlyReplyToNewsgroup@notmail.com> wrote in message
news:u1ybAb3cKHA.5156@TK2MSFTNGP04.phx.gbl...
> Csaba Gabor wrote:
>> I'd like to determine the number of bits (the position
>> of the highest on bit) in a negative number (say -1)
>> without using knowledge of its type.
>>
>
> The "brute force" way would be to "shift left" one bit
> at a time, until you hit your 1-bit.
>
> Problem is, you can't shift left in script.  There are
> a number of shifting functions written in VB, but they
> require calling the system api.
>
> Most scripters abhor calling the system api, and so
> your best bet is to wait around for a more knowledgable
> person to come along with a "pure script" solution.

If the task must be done without using "knowledge of its type", then double
precision floats might be involved, which could be a lot of bits that don't
shift nicely.

```
 0
Paul
12/2/2009 10:17:13 PM
```On Dec 2, 6:46=A0pm, mr_unreliable <kindlyReplyToNewsgr...@notmail.com>
wrote:
> Csaba Gabor wrote:
> > I'd like to determine the number of bits (the position
> > of the highest on bit) in a negative number (say -1)
> > without using knowledge of its type.
>
> The "brute force" way would be to "shift left" one bit
> at a time, until you hit your 1-bit.
>
> Problem is, you can't shift left in script. =A0There are
> a number of shifting functions written in VB, but they
> require calling the system api.

You can shift left in VBScript - Just multiply the
number by 2.  The problem is that if you have
2^14 (as an integer) and you shift left by 1 it becomes
a long so that the sign does not go negative.  And
while this isn't a problem with positive numbers, it is
a problem with the negatives, since the sign keeps
getting extended.  In other words, as you keep
multiplying your bit selector by 2, it will eventually
turn from an integer to a long.  When you and or
xor it with the number being tested, that in turn will
turn into the type matching the selector, extending
any leading 1s for negative numbers.  Nevertheless,
this is the approach that I've used.

The highest bit position for a negative number is given
by the highest bit position for a -1, which can be
trivially givien if one presumes to know how many
bytes it takes to represent a given type.  But that's
what I didn't want to tie myself to.

> Most scripters abhor calling the system api, and so
> your best bet is to wait around for a more knowledgable
> person to come along with a "pure script" solution.
>
> cheers, jw
```
 0
Csaba
12/3/2009 12:17:57 AM
```On Dec 2, 7:27=A0pm, Tom Lavedas <tlave...@gmail.com> wrote:
> On Dec 2, 12:46=A0pm, mr_unreliable <kindlyReplyToNewsgr...@notmail.com>
> wrote:
>
> > Csaba Gabor wrote:
> > > I'd like to determine the number of bits (the position
> > > of the highest on bit) in a negative number (say -1)
> > > without using knowledge of its type.
>
> > The "brute force" way would be to "shift left" one bit
> > at a time, until you hit your 1-bit.
>
> > Problem is, you can't shift left in script. =A0There are
> > a number of shifting functions written in VB, but they
> > require calling the system api.
>
> > Most scripters abhor calling the system api, and so
> > your best bet is to wait around for a more knowledgable
> > person to come along with a "pure script" solution.
>
> > cheers, jw
>
> JScript has SHIFT operators, so the old trick of using JScript in VBS
> will work ...
>
> wsh.echo ShiftRight(clng(-1) and &h7fffffff&, 30)
>
> Function ShiftRight(arg, n)
> =A0 with createobject("htmlfile")
> =A0 =A0 .write "<script>var a=3D" & arg & ">>" & n & ";</script>"
> =A0 =A0 ShiftRight =3D .parentWindow.a
> =A0 end with
> end function
>
> Function ShiftLeft(arg, n)
> =A0 with createobject("htmlfile")
> =A0 =A0 .write "<script>var a=3D" & arg & "<<" & n & ";</script>"
> =A0 =A0 ShiftLeft =3D .parentWindow.a
> =A0 end with
> end function

Hi Tom,
VBScript can do JS style of shifting just fine, I think:
For shift left, just multiply by 2 (or add the number to itself),
which should work for both positive and negative integers.

For shift right, the situation is a bit more complicated.
It amounts to a floor operation after division by a power of 2:
x >> n is:
x AND (-1 XOR 2^n-1) / 2^2
Though the type of notation I've used may cause the type
of the result to change (since 2^n produces a double, for
example).

> I also propose ANDing the number (converted to a Long - 32 bit -
> number) with a mask that zeros the minus sign bit. =A0Then the other

This is what I'm trying to avoid.  You have presumed to know
where the high bit is already (in the case of negative numbers).

> bits can be tested. =A0The shift that first returns a value of zero is
> the most significant bit (I didn't bother to show the test loop).

> BTW, your shift nomenclature seems backward to me. =A0I guess you were
> thinking of shifting the mask and not the number. =A0However, starting
> from the MSB end would still seem most efficient and would still shift
> the mask to the right, not the left wouldn't it?

Your conclusion is only valid if you presume you know where the
high bit must be (in which case you will get a trivial answer for
negative numbers, but no clear win for positive numbers).  However,
the bit shifting approach from right to left must have a basis for
termination, which is the hard part, I think.
```
 0
Csaba
12/3/2009 12:42:58 AM
```On Dec 2, 11:17=A0pm, "Paul Randall" <paulr...@cableone.net> wrote:
> "mr_unreliable" <kindlyReplyToNewsgr...@notmail.com> wrote in message
>
> news:u1ybAb3cKHA.5156@TK2MSFTNGP04.phx.gbl...
>
>
>
>
>
> > Csaba Gabor wrote:
> >> I'd like to determine the number of bits (the position
> >> of the highest on bit) in a negative number (say -1)
> >> without using knowledge of its type.
>
> > The "brute force" way would be to "shift left" one bit
> > at a time, until you hit your 1-bit.
>
> > Problem is, you can't shift left in script. =A0There are
> > a number of shifting functions written in VB, but they
> > require calling the system api.
>
> > Most scripters abhor calling the system api, and so
> > your best bet is to wait around for a more knowledgable
> > person to come along with a "pure script" solution.
>
> If the task must be done without using "knowledge of its type", then doub=
le
> precision floats might be involved, which could be a lot of bits that don=
't
> shift nicely

Only integers (but not integer types are presumed).
When I posed the question, I didn't have a solution - this
problem has been bugging me since around the time of
too harsh, and really meant that one shouldn't presume
knowledge of any specific type (as opposed to knowing
its type).  So I programmed up a solution based on
detecting a type change.  Still, I was not happy with
this, so in writing this up I have produced the following
which has worked for all my test cases, and about which
I am less unhappy (improvements welcome):

MsgBox HighBitPos (0)        '-1
MsgBox HighBitPos(27)         '4
MsgBox HighBitPos(16384)     '14
MsgBox HighBitPos(2^14)      '14
MsgBox HighBitPos(32768)     '15
MsgBox HighBitPos(2^15)      '15
MsgBox HighBitPos(-1)        '15
MsgBox HighBitPos (-&1&)     '15
MsgBox HighBitPos(&H10FFFF)  '20
MsgBox HighBitPos(-&HFFFF&)  '31

Function HighBitPos(n)
HighBitPos =3D -1
On Error Resume Next
Dim bit, typ: bit=3D1: typ=3Dtypename(n)
While typ=3Dtypename(n) AND n<>0
HighBitPos =3D HighBitPos + 1
If (n AND bit) Then n =3D n XOR bit
If n =3D -n OR bit=3D-n Then exit Function
bit =3D 2*bit
Wend
'  HighBitPos =3D HighBitPos & " " & typ
End Function

Csaba Gabor from Vienna
That on error is there because of the last
case.  When missing, it will die on the first If.
```
 0
Csaba
12/3/2009 1:19:10 AM

Similar Artilces:

Email Subject Auto Number ?
Hi I need Your Help 1. When i send an email through the activities it sent with an automatic number in the subject. what this number means ? How can I take it off ? after I'll take it off what does it means ? the return email would not be related to the entity ??? 2. I have an attachment in the note in the opportunity entity How can I send an email with this note as the attachment of the mail ??? -- Thx very much , Omry Hi Omry, The number you see in the subject line of the email is the tracking token. This will be used to identify the email as a CRM activity and relate it to an ac...

Display one number in a cell even though 2 numbers get pasted into the same cell? #2
Ok. Maybe I didn't explain myself thoroughly. I don't care about the second number. I just want to get rid of th second number in the cell and only keep the first. Can I do this by using Data - Seperate Text into columns? If so, ho do I do this? Any other possible suggestions? DrSues0 -- DrSues0 ----------------------------------------------------------------------- DrSues02's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=1256 View this thread: http://www.excelforum.com/showthread.php?threadid=26621 Yep. Select that column of cells. data|text t...

Number of emails in a folder
For some reason Entourage does not tell me how many emails are in a folder on the IMAP server and I had to log into the web based client to see this. Can Entourage tell me this? John -- Are there errors in the Bible? Do Animals go to Heaven? Is drinking Alcohol a sin? Is the KJV the only translation to be used? If you want to learn, get answers, and be able to defend the faith, CERM is your place. http://www.cerm.info/ John Wolf wrote: > For some reason Entourage does not tell me how many emails are in a folder > on the IMAP server and I had to log into the web bas...

Filter Records not Begginning with Numberic Characters
My table has a Street address field. I would like to filter out records that do not begin with a numeric Character. Also if possible I would like to filter records that do not have a space between the numeric characters and the alpha - Example: 123Street I would try WHERE StreetAddress Not Like "[0-9]*" or StreetAddress Not Like "*[0-9] *" John Spencer Access MVP 2002-2005, 2007-2010 The Hilltop Institute University of Maryland Baltimore County Jeff wrote: > My table has a Street address field. > I would like to filter out records that do n...

How can I add numbers in my text files made by my MFC app ?
I want my MFC app to add the numbers in my saved text on saving time like this... 1:here 2:test 3:hello 4:hehe 5:pizza 6:hi Thanks, BMXer This is just example code I found on google. #include "stdafx.h" #include "string.h" int countLines(char filename[]); int main(int argc, char* argv[]) { int lineCount; char filename[80]; strcpy(filename, "test.txt"); lineCount = countLines(filename); printf("Lines in %s: %d\n", filename, lineCount); return 0; } countLines(char filename[]) { FILE *fileRef; int lineCount = 0; char fileLine[256]; ...

Random numbers #4
I would like to assign random numbers to a list of names. I tried using Randbetween, but it allows numbers to be repeated. Is there a way to assign numbers without any repetition? See: http://www.mcgimpsey.com/excel/udfs/randint.html HTH Jason Atlanta, GA >-----Original Message----- >I would like to assign random numbers to a list of names. I tried using >Randbetween, but it allows numbers to be repeated. Is there a way to assign >numbers without any repetition? >. > ...

determine mail flow problem!!!!!!!!
Help! :-( Our mailflow from 2 backend 2003 exchange servers keeps queuing up in the outbound queue (which is set to always run delivery). Messages stay in there from 10 to 120 minutes before being sent to our gateway MTA and then sent off site (to hotmail.com for example). However when I telnet from a backend server to the gateway over port 25 and send a test message it goes right away. I can't for the life of me figure out why. One example when viewed in message tracking history says: 10:16am - smtp: store driver, message submitted from store 10:16am - smtp: message submitted to ...

ID number for all emails
We have a need to have all emails have a unique id number so they can be tracked - does anyone know if this is possible? All items in Outlook are uniquely identified by a combination of the EntryID of the item. This is a constant unless the item has been moved (it remains the same if moved in a PST file) in an Exchange mailbox or public folders store. In addition, each item has a ConversationIndex property that in combination with the ConversationTopic property. Those could be used. Other than that you could generate your own unique series of tags for items by using a database table's ...

Customise field to show as % or round up the numbers
Hi, I am trying to add a new field / attribute to CRM quote entity. This field will be showing the profit margin on the quote form. Is there anyway for me to format the field, so it will appear as %? And if it is all possible for the calculation to round up to the next number? Ta! Sindy There's no default format option to do that, so you would have to use the OnLoad and OnChange javascript events to format and round up your field. HTH, -- Jeffry van de Vuurst CWR Mobility www.cwrmobility.com -- SW wrote: > Hi, > I am trying to add a new field / attribute to CRM quote entit...

Determine columns used
I have 100+ spreadsheets which i have to edit into a certain format. The spreadsheets currently have 100 columns (from 1-100). From there i have to reduce the number of columns set to 8 columns. E.g: 1 2 3 4 5 6 7 8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 (from column 9 onwards, it goes to the 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 next rows' column 1) 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 How do i do that without altering the order of the value of the cell? Let me make sure we understand the question. You have ...

Default number format
Is there a way to change the default NUMBER format for new workbooks? I found the default FONT, but not default NUMBER format. Dave French David Open a new workbook. Customize as you wish. File>Save As Type: scroll down to Excel Template(*.XLT) and select. Name your workbook "BOOK"(no quotes). Excel will add the .XLT to save as BOOK.XLT. Store this workbook in the XLSTART folder usually located at........ C:\Documents and Settings\username\Application Data\Microsoft\Excel\XLSTART This will be the default workbook for File>New>Workbook. You can also open a new wo...

Dynamically determining when a month ends
Hello all, Ok, I have a simple excel spreadsheet, where I keep track of my spending on one tab, my income in another and my summary in a thrid. My problem happens when I try to dynamically calc. avg's for months in the summary page. For instance, if I want to see how much money I spent on average per month, or even per day, I draw from the data entered into the spending page. Now, the spending page is set up with the following columns: Date:: Description:: Amount The problem with this is that I can't predefine a max row # for each month, since I might have 80 entries in spending...

Modification of Part Number (Revised)
I would like to add the string "1212" (no quotes) to some part numbers. Essentially, I have two versions of part numbers to modify: xxxxxxx(space)(space)xxxxxxxxxx(space)xxxxx(space)xxxx or xxxxxxxxxx(space)xxxxx(space)(space)xxxxxxx(space)xxxx(space)xxxx The length of the xxxxxx strings varies and represents alphanumeric characters that must remain unchanged. The string "1212" (no quotes) must always be appended to the first xxxxx string of alphanumeric characters. Thus the end result of the modification should be as follows: xxxxxxx1212(space)(space)xxxxxx...

Verifying number of records for upgrades/migrations
I have the following script from an MBS upgrade manual, which works great: Select name, rows from sysindexes where indid in (0,1) order by name However, we need to change our sort order to case-insensitive, according to the TK on CUstomersource using BCP. I have done this a couple times, but after you bcp the data out, then in, the number of records signicantly changes because the script is looking at the sysindexes table. Is there a script that we can run to look at the number of records within all user-defined tables, instead of the number of indexes? I don't feel comfortable...

Page numbers don't appear in subreport
Hi all, I have a simple problem with a report. In the page header of the report I list page x of z in the usual fashion. However, the report contains a subreport and if that subreport runs into multiple pages the main report page header doesn't print the page number on those pages. Any ideas to force the main report page header to print on every page even if the only data on the page is from the subreport? Dannasoft wrote: > Hi all, > > I have a simple problem with a report. In the page header of the > report I list page x of z in the usual fashion. Ho...

how to determine the size of the sheet
Hi I had a collegue who told me once a way to dtermine the number of the rows in a sheet of the workbook I am working at. It is known that when you open a new workbook each sheet has maybe 65365 or something like that rows. MY QUESTION IS: HOW TO MAKE THE SHEET 1000 ROWS OR WHATEVER NUMBERS OF ROWS I ONLY NEED? Thanks in Advance, Ahmed Hi Ahmed The number of rows and columns are fixed. Your workaround would be to hide the ones you consider unneeded. HTH. Best wishes Harald "Ahmed SHEBL" <ahmad.shebl@hotmail.com> skrev i melding news:%231uFO3IcHHA.4720@TK2MSFTNGP0...

vc++ 6.0 application runs on windows 20003 (64 bit CPU 32 bit OS)
Hi I have a VC++ 6.0 application runs on windows 20003 (64 bit CPU and 32 bit OS), it does not work. The same application runs fine on Windows XP and Windows 2000. When I debug it with VC++ 6.0, the break points and the source code totally messed up. I have a if else statement, the debug goes from inside if goes to else block if (...) { ....................... } else { ............... } Does any one have any idea about this? Thank you for your help There is no content whatsoever in the phrase "does not work". There is always a specific statement as to why something do...

length of check number
I recently got a new set of paper checks that started at #50000. When I download the cleared check information for these, MS Money is truncating the check number - so 50001 became just 1. Is this a known issue? I contacted Wells Fargo, but they didn't know anything about it. I can edit the check number and change it to 50001, so it seems to be able to hold that number of digits. Any pointers/suggestions would be greatly apprecaiated. Henry I'm betting if you checked the downloaded data, Wells Fargo is truncating it not Money. "Henry Winkler" <Henry Winkler@di...

How to extract the Number from a String
Hello friends I have a column with following type of data: 1243 no. of Books 213 no. of Pens What i want is to extract only the numeric data from the column and keeping the the original string as it is thanks in advance johnbest -- johnbest ------------------------------------------------------------------------ johnbest's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=29694 View this thread: http://www.excelforum.com/showthread.php?threadid=494535 Hi John Assuming your data always has a space after the last numeric value, and with the data in A1 =--LEF...

Turn off Automatic Check numbers?
Does anyone know how to turn off the Automatic Check numbering within a checking account? This is particularly annoying when we put in a new withdrawal for a ATM Cash withdrawal or direct debit and a check number comes up. ...

when I type a long number it shows up as smaller number and +
when converting from xls to csv format, some of my longer mortgage numbers get condensed into a smaller number with a letter, a plus sign and another number. example: 100020013120 turns into 1.0002E+11. Any way to get rid of this? Thanks, Yes, just specify the format that you want. Format Cells...>Number>0 decimal places Regards, Fred "SandyC" <SandyC@discussions.microsoft.com> wrote in message news:FA52E426-360E-4BE5-B63B-1209E673CA65@microsoft.com... > when converting from xls to csv format, some of my longer mortgage numbers > get conde...

Change outline numbering, hanging indent not updated
I followed http://www.shaunakelly.com/word/numbering/OutlineNumbering.html to define an outline numbering scheme. For each additional outline level, I added 0.12" of extra indentation for the text of the heading. The tabstop settings are properly updated in each Heading style, but the hanging indents is not. I manually modified the hanging indents to match the tab settings. Is there a more intelligent way to have the hanging indents update automagically? When you apply outline numbering to paragraph styles, the indents and tabs must be set in the Numbering dialog, not in the...

Displaying a 12-digit Number
How can I have a cell display a 12-digit number? Currently, when you would type the number 123456789012, 1.23457E+11 is displayed. As I need to have the spreadsheet saved as a Text Delimited file, even when formatting the cell as text does not work, because when the file is being converted, it sees the cell as a number, and brings me back to square one. Any ideas?? Thank you. Hi format the cell with the custom format 000000000000 -- Regards Frank Kabel Frankfurt, Germany John wrote: > How can I have a cell display a 12-digit number? > Currently, when you would type the numbe...

How do I determine
I have X number of rows that show employee names and a column (A2) that lists the value of products sold by each employee and I want to pay them a percentage based upon value of sales. For example: If they sell up to =A31,000 worth of products, I will pay them 3% of the value. Between =A31,000 & =A32,000, I will pay them 5% of the value Over =A32,000, I will pay them 10% of the value The amount paid to them in commission will be show in column (A3). Many thanks D.Haste darren.haste@ttt.co.uk "Hastey" <darrenhaste@sky.com> wrote in message news:6a0a4fa9-adcd-484a-80...

How do I update a spreadsheet with numbers input into another?
How do I link two speadsheets in order to update both at the same time? "Duma" wrote: > How do I link two speadsheets in order to update both at the same time? Probably something like this In Sheet2, In A1: =IF(Sheet1!A1="","",Sheet1!A1) Copy A1 across/down to cover the extent Sheet2 will then reflect entries/updates in Sheet1 for the formulated range -- Max Singapore http://savefile.com/projects/236895 xdemechanik --- If both spreadsheets are the same, headers, data ranges, titles etc, basically same architecture on both sheets, then... While on Sheet1...