Solved

Converting long to a fixed length string

Posted on 1998-05-30
13
365 Views
Last Modified: 2010-04-15
How do you convert a long to a string with a length of 4 and how do you convert it back to a long?

                              Sheila
0
Comment
Question by:baileys
  • 6
  • 2
  • 2
  • +2
13 Comments
 
LVL 11

Expert Comment

by:alexo
Comment Utility
Several options: sprintf(), ltoa(), atol().
Details comming...
0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
Using sprintf():

    char buffer[20];
    long num = 1234L;
    sprintf(buffer, "%4ld", num); /* "Percent Four El Di" in case the font is not clear */

sprintf() will not cause the result to be truncated (so make sure the original long is less than 10000 but larger than -1000 if you want it to fit in 4 spaces) but will pad the value to the right with spaces.  If you want left padding (right justification), use "%-4ld".  If you want leading zeros instead, use "%04ld".

Using sscanf():

    char* string = "4567";
    long num;
    sscanf(string, "%4ld", &num);

This will convert the first four numerical characters in the string into one long.

0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
Disregarding the length, you can use more efficient functions:

    char* string = "9876";
    long num = atol(string);

and

    char buffer[20];
    long num = 9876L;
    ltoa(num, buffer, 10); /* Calculation is decimal - base 10 */

0
 

Author Comment

by:baileys
Comment Utility
I am converting Ada code to C.  I am not allowed to modify the file structures.  There are two Ada procedures that uses the "unchecked_conversion" procedure that converts one type of data to another type of data and back(without type checking or any checks) without losting the integrity of the data.  One of the Ada functions takes a string date in the format of "YYYYMMDDHHMMSS" and converts it to a long, which represent the number of seconds since Jan 1, 1970.  This long is then converted to a 4 byte string(using the "unchecked_conversion" procedure) which is stored in the database.

The second Ada procedure reverses the process.

Now, the big question is, how to do this in C?  The long HAS to fit into a 4 byte string.
                      Sheila
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
/* I don't know if this stores the same string as the Ada procedure, but it's certainly unchecked */

#include <string.h>
 
char string[4];
int num=896549100;
memcpy(string,&num,4);

memcpy(&num,string,4);
printf("%d\n",num);
0
 
LVL 11

Accepted Solution

by:
alexo earned 200 total points
Comment Utility
You don't want to convert it to a string, you just want to use it as 4 bytes.
I suggest a cast.  Given a pointer to a long, convert it to a pointer to characters.  Then use the 4 characters from that pointer.  Remember, C strings are zero terminated so treating the "raw" 4 bytes as a string will fail if one of them is a binary zero.

    long num = 1234567890L;
    char* p = (char*)&num;

p[0] .. p[3] are the four bytes.

0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 10

Expert Comment

by:RONSLOW
Comment Utility
I doubt that it is a four byte string (in the sense of a text string).  Rather it is just four bytes.  In that case, there is no conversion necessary ... a long is already four characters long.

The problem is that, for string manipulation function in C, a zero byte indicates the end of the string.

However, C also includes library functinos for working with arrays of bytes.  For example, you can use strcpy to copy a null terminated string, but memcpy to copy a fixed number of bytes.

If you REALLY need to convert the long to a 'string' of for bytes. then you can say someting like this...

union LongAs3Bytes {
  long lval;
  struct {
    char byte[4];
  } array;
}

then you can say ...

  LongAs4Bytes x;
  int i;
  x.lval = 1234;
  for (i = 0; i < 4; i++) {
    char b = x.array.byte[i];
    // etc
  }

alternatively, you can simply cast
  long l = 1234;
  int i;
  char* array = (char*)l;
  for (i = 0; i < 4; i++) {
    char b = array[i];
    // etc
  }

However, I think (from your description) that you can simply read and write the long directly .. and it will be read/written as four bytes.

As for the conversion from a date format to a long, there are C library functions that will help with this .. alternatively, look at www.snippets.org for appropriate routines.

Please let me if I have understood your problem correctly and have been of any help (or can be of any more)

If so, and you wish to grade me, remember that you must reject previously proposed answers first .. or get in touch with EE customer service and request a split of points.

Roger

0
 

Expert Comment

by:rikonigsberg
Comment Utility
One thing you might want to consider is that just because the Ada program stores the data as four bytes doesn't mean that by overlapping them onto a C long variable will give you the correct information, especially if the data comes from a different operating system or compiler. Here is a prime example:

Suppose that the data was stored high-byte first. In other words, the number 00 00 00 FF might actually need to be mapped to FF 00 00 00.

This sort of stuff does come up, so if you are getting wrong answers, this might be why.

As a "worse" example, it might store bit information in reverse order. So,

Binary 10000000 00000000 00000000 01010101
Hex    8   0    0   0    0   0    5   5
Might need to be stored as:
Binary 10101010 00000000 00000000 00000001
Hex    A   A    0   0    0   0    0   1

(See how the BITS themselves are reversed?)

Just keep all this in mind. Also, are you sure your local compiler has long stored as four bytes?

Jes keeping you on your toes.

Rob
0
 

Author Comment

by:baileys
Comment Utility
How do I get contact EE customer service?
0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
>> How do I get contact EE customer service?
Post a 0-point question in the "experts exchange" area.

>> Suppose that the data was stored high-byte first
The "endianness" rikonigsberg refers to is dependent only on the processor, not programming language, compiler or OS.

>> As a "worse" example, it might store bit information in reverse order.
Never!

0
 

Expert Comment

by:rikonigsberg
Comment Utility
>> >> Suppose that the data was stored high-byte first
>> The "endianness" rikonigsberg refers to is dependent only on >> the processor, not programming language, compiler or OS.
>>
>> >> As a "worse" example, it might store bit information in
>> reverse order.
>> Never!  

Perhaps. Like I said, I'm just throwing out a warning just in case the data did come from another source, and a straight mapping doesn't seem to work. Though it might be the case that pure reversal of the bits, reversal of the bytes could occur because the data could come from being processed on another processor. When I was referring to separate OSes, I was not referring to Win95 vs WinNT, but rather varying Unix operating systems. Details are sketchy off the top of my head, but there you go.

And yes, I couldn't remember the name "endian" :)
0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
And the autograder hits again!
0
 
LVL 10

Expert Comment

by:RONSLOW
Comment Utility
Gees .. that autograder is a busy chap !! :-)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now