473,795 Members | 2,919 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Fixed BCD code.

Cause I made such a hash of my first attempt, and in an effort to provide
PORTABLE code to solve the problem, I submit this solution to convert to
and from BCD values stored in longs. This should work just as well for
ints and (in theory) chars and, indeed, any integral type. If it doesn't,
suggest ways to improve it, even at a significant speed/code size penalty.

#include <math.h>

long bcd(long decimal)
{
int i;
long result = 0;

for(i = 0; decimal; ++i) {
result += (decimal % 10) * (int) pow(16,i);
decimal /= 10;
}

return(result);
}

long dec(long bcd)
{
long result = 0;
int i;

for(i = 0; bcd; ++i) {
result += (bcd % 16) * (int) pow(10,i);
bcd /= 16;
}

return(result);
}

/* Code tested on all of one machine, but C is portable in theory. */

Nov 13 '05 #1
2 9222
In article <Xn************ *************** *******@63.223. 5.101>,
August Derleth <li************ *****@onewest.n et> wrote:
Cause I made such a hash of my first attempt, and in an effort to provide
PORTABLE code to solve the problem, I submit this solution to convert to
and from BCD values stored in longs. This should work just as well for
ints and (in theory) chars and, indeed, any integral type. If it doesn't,
suggest ways to improve it, even at a significant speed/code size penalty.

#include <math.h>

long bcd(long decimal)
{
int i;
long result = 0;

for(i = 0; decimal; ++i) {
result += (decimal % 10) * (int) pow(16,i);
pow(16, i) returns a double, which you then cast to an int. There is
no guarantee that either has as much precision as a long. Instead:
result += (decimal %10) << (4 * i);
(Also offers the performance benefit of not converting back and forth
between floating point and integer.)

For similar reasons:

long dec (long bcd)
{
long result = 0, i = 1;

while (bcd) {
result += bcd % 16 * i;
i *= 10;
bcd /= 16;
};
}
/* Code tested on all of one machine, but C is portable in theory. */


Only when you don't make assumptions about implementation-defined
portions of the standard.

-- Brett
Nov 13 '05 #2
rb*@panix.com (Brett Frankenberger) wrote in
news:bj******** **@reader2.pani x.com on Fri 05 Sep 2003 09:04:00p:
In article <Xn************ *************** *******@63.223. 5.101>,
August Derleth <li************ *****@onewest.n et> wrote:
for(i = 0; decimal; ++i) { result += (decimal % 10) * (int)
pow(16,i);


pow(16, i) returns a double, which you then cast to an int. There is
no guarantee that either has as much precision as a long. Instead:
result += (decimal %10) << (4 * i);


Ah, but will the shifts be portable to machines that use, say, multiples
of three for their word-size? Will my multiplies?

I can't think of how BCD would work in an octal system (where you'd only
have three bits to encode each digit*), or on a hypothetical ternary
system (which /good/ C code is supposed to be portable to).

Is the problem itself limited to certain kinds of systems?

*Three bits only gives you eight numbers. Nine bits is 8+1, giving you the
possibility of encoding one `traditional' BCD digit with the option of a
sign bit. You can do the math from there.
/* Code tested on all of one machine, but C is portable in theory. */


Only when you don't make assumptions about implementation-defined
portions of the standard.


Touche'.
Nov 13 '05 #3

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

Similar topics

26
9702
by: Adrian Parker | last post by:
I'm using the code below in my project. When I print all of these fixed length string variables, one per line, they strings in questions do not properly pad with 0s. strQuantity prints as " 4". Six spaces than the value of intQuantity. This is correct. But all the others end up being string objects of only 6 characters long (with the exception of strTotal). The left most positions of the string object are being padded with one...
1
3528
by: Jaz | last post by:
Trying to use a fixed layer for a couple of NAV buttons. I found this code, but the IE part is commented, and I don't understand the IF statement. It works great on Moz/Firebird and Opera BUT not IE. Would someone please take a look at this and tell me if it can made to work in IE? If it can, a hint on the syntax/code would be much appreciated! PS, this would also get rid of my fixed background. Thanks in advance Jaz
6
5409
by: Mason A. Clark | last post by:
Masters: On two or three-column layouts, one column often has a list of links. Scrolling the page hides them. I'm aware there's supposed to be the ability to fix the column (frame-like). I have some bits of such code but haven't yet made it work well. Question: Why have I never seen an example on the web? Not that I've seen everything, but I've seen numerous pages
5
8324
by: Arthur Mnev | last post by:
This is probably beaten to death subject... Does anyone have a good idea of what penalties are for using Fixed statement in c#. On one side it allows for much greater flexibility with casts and array manipulations (i'm leaving access to legacy code out of the scope of this message) on the other hand fixed statement does consume resources to execute, not to mention if "everything" is fixed, then dynamic object reallocation becomes...
3
2309
by: Dave | last post by:
I have the following code in one of my programs; ert= CO3; int Code = SR(ert, 1024, 1024); char UnsafeTempBuffer = new char; fixed ( char* tBuffer= UnsafeTempBuffer) { Code = Siofunc(tBuffer, 128); }
2
11202
by: coz | last post by:
I created a wrapper class for a dll written in C. Will the following code prevent the "ENTIRE ARRAY" from being moved, not just the first array element? The Wrapper class will be instantiated in a VB .NET application which doesn't have the ability to prevent the array from being moved. Thanks in advance, coz public class Wrapper {
3
2755
by: Chris Dunaway | last post by:
I was using .Net Reflector to look at some methods in the String class and found this one: Friend Sub AppendInPlace(ByVal value As Char*, ByVal count As Integer, ByVal currentLength As Integer) Dim local1 As Char* Fixed local1 = AddressOf Me.m_firstChar Dim num1 As Integer For num1 = 0 To count - 1 local1((currentLength + num1)) = value(num1)
4
2205
by: taskswap | last post by:
I'm converting an application that relies heavily on a binary network protocol. Within this protocol are a lot of byte arrays of character data, like: public unsafe struct MsgAddEntry { public byte MsgType; public uint Tag; public fixed byte ID; public fixed byte Val1;
0
1525
by: Ken Varn | last post by:
I have a managed C++ assembly in which I need to interact with some 'C' APIs that take fixed size 'C' data blocks. I need to wrap these data blocks into a managed object. It seems like a lot of redundancy and extra code to have to marshal .net data from managed to unmanaged for this. Is there some built-in method in managed C++ that can allow me to create a managed structure and convert it into a fixed size 'C' data block? I am trying...
1
9436
by: Rick Knospler | last post by:
I am trying to convert a vb6 project to vb.net. The conversion worked for the most part except for the fixed length strings and fixed length string arrays. Bascially the vb6 programmer stored all form data in a fixed length structure that is written direct to disk. I need to load the existing files, into a fixed length structure to initialize the form data within the project. I am running into problems with statements like the...
0
9673
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9522
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
10443
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...
1
10165
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
10002
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
6783
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();...
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2921
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.