473,785 Members | 2,465 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Integer to "string" conversions

Now, I read the faq, and it suggests using sprintf. However,
I want to all ways know where the integer finishes in the string.
Basically, I want to:

nbr | other data

But the other data all ways has to start at the same place. I had
some problems using sprintf to accomplish this requirement. Maybe
I am overlooking something. But sprintf translates the nbr exactly
into
the string, so the nbr 123, would end up occupying:

p[0] = '1'
p[1] = '2'
p[2] = '3'

So as the number grew, the space taken grew.

To solve this, I went with the solution below. But this would require
me
to OR back the number later. Is there a better way to do this?

Note: I am using uint32_t to signify a 32 bit unsigned integer. This
is implementation
specific, but for the sake of this discussion, I need to know
the size
of the integer being assigned to buf ahead of time. I am also
ignoring
dynamically allocated arrays for this discussion as well.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(void) {

int i;
uint32_t nbr;
unsigned char buf[4];

nbr = 0xffffffff;
memset(buf, 0, sizeof buf);

buf[0] = (unsigned char)(nbr >24) & 0xff;
buf[1] = (unsigned char)(nbr >16) & 0xff;
buf[2] = (unsigned char)(nbr > 8) & 0xff;
buf[3] = (unsigned char) nbr & 0xff;

for(i = 0; i < 4; i++)
printf("%d\n", buf[i]);

exit(EXIT_SUCCE SS);
}

Sep 30 '06
13 6880

Christopher Layne wrote:
CBFalconer wrote:
I thought you were complaining that the field used varied with the
value. If you don't want the leading zeroes, remove the '0'.

As far as I could tell, he was looking for a way of encoding "size" in a fixed
length method that would be network-portable. snprintf() could be used for
that, in a rather bizarre, inefficient, and roundabout way.
True. But I wanted to leave the network related items off this
newsgroup. And
I have read Stevens' book.

Oct 1 '06 #11
bw*****@yahoo.c om wrote:
True. But I wanted to leave the network related items off this
newsgroup. And
I have read Stevens' book.
Understandable. But why even consider such a ridiculous way of encoding when
the tried and true method is both more efficient, lower overhead, and more
natural?
Oct 2 '06 #12

Christopher Layne wrote:
Understandable. But why even consider such a ridiculous way of encoding when
the tried and true method is both more efficient, lower overhead, and more
natural?
What's the tried and true method? I did not get a lot out of Stevens'
when it comes
to protocol design. I saw a lot of different approaches to the
blocking problem.
But I never considered using writev or readv to build a protocol. I
figured I would
just write the protocol stuff to the front of the buffer and read it on
the other end
after doing any network translation as needed.

So you would build all your protocol information into struct iovec?
Basically, I was
thinking of sending only a few items: crc or sha1, file size, and file.
I was going
to buffer this out at the page size or twice the page size. My
approach to handling
the blocking problem was to use pthreads. Once this worked, my next
step was
to use ssl.

Of course, all of this is off topic here.

Cheers!

Oct 2 '06 #13
bw*****@yahoo.c om wrote:
So you would build all your protocol information into struct iovec?
I mainly use iovec's because they are natural for this purpose and also
because of the win/win of not having to marshal data into a temporary buffer
(don't even think of sending a struct over the network either) and/or call
read() more than once. That's the main goal of readv()/writev().
Basically, I was
thinking of sending only a few items: crc or sha1, file size, and file.
I was going
to buffer this out at the page size or twice the page size.
No need to do this really, that is page size buffering, etc. - atleast for the
transmission side. What one typically does is handle things via typical
realloc() and keep that larger buffer around for the life of the program or
downsize it to an average size seen, bordering a page boundary. As far as the
protocol itself, a basic protocol will revolve around TLV encoding + 1 main
header and possibly a trailer (although unlikely). Keep things small but not
so small there is no room for future expansion - and possibly consider a
version byte, or short.
My
approach to handling
the blocking problem was to use pthreads. Once this worked, my next
step was
to use ssl.
Let me give you some guidance here, as I have direct experience with it,
including pthreads + socket programming. Attempting to use threads (let's say
thread per connection) as a method of getting around blocking is going to
result in eventual pain - and not because of threading - just that one cannot
100% trust select(). The best way to get around blocking issues is to do just
that - write non-blocking handlers. If you need example code for all basic
socket routines, let me know - but I highly recommend writing your own first
so you can make the common mistakes and figure out they were made. It's
really not total rocket science, but don't make any assumptions. This is
where UNPv1 will come in extremely valuable. For a while I thought my
readv()/writev() routines would never return a partial read or partial write
space available error. It only took one serious stream of data above the MTU
to prove this wrong. This particular situation was only a tad more difficult
than normal as prior-documentation for it wasn't really out there on the net
(for readv()/writev() specifically). Like I said, just don't even bother with
blocking mode.
Of course, all of this is off topic here.
Yep, comp.unix.progr ammer. Followed up.
Oct 2 '06 #14

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

Similar topics

32
2694
by: Indrid Colt | last post by:
Thank's for your help ! Indrid
9
7135
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but when I tried the program on the Win98 system it will be running on, I get the following error: Cast from string "2076719" to type 'Long' is not valid I am not sure why I only get this error on the Win98 system or how to go about correcting...
35
75225
by: pinkfloydhomer | last post by:
How do I check if a string contains (can be converted to) an int? I want to do one thing if I am parsing and integer, and another if not. /David
4
13778
by: dc15 | last post by:
For an intro to VB project I have to write a program which takes an amount of Miles, Yards, and Inches.....and converts it to metric (KM, M, and CM) when all values are entered to the input text boxes it works fine, but if there is a number missing I get the following error: An unhandled exception of type 'System.InvalidCastException' occurred in microsoft.visualbasic.dll Additional information: Cast from string "" to type 'Double' is...
10
13643
by: =?Utf-8?B?RWxlbmE=?= | last post by:
I am surprised to discover that c# automatically converts an integer to a string when concatenating with the "+" operator. I thought c# was supposed to be very strict about types. Doesn't it seem like c# is breaking its own rules? This works: int b = 32; string a = "ABC " + b; Result: a = "ABC 32"
3
5033
by: Ady1 | last post by:
Hi, I'm getting this error intermitantly in a custom configuration section in my ASP.NET website. From what I can see 0.175 is a valid string to be converted to a decimal! And most of the time it works, so why is it that about once a week for about half an hour I get this error? Any Ideas? Thanks, Ady
6
4594
by: =?Utf-8?B?SmVmZg==?= | last post by:
I thought this would already be covered here, but my search turned up nothing. In VS2005, if I use "String" to define a new variable/class, it colors it in the Aqua color as it does other classes. But if I use "string", it colors it in Navy blue as in C# reserved words (e.g. private, void, foreach, etc). What is the diff?
10
26909
by: Dave griffiths | last post by:
Hi all Using VB2005 on Vista with a Norwegian locale setup. The test program has 3 textboxes the sum held in txt3. Using the code below, txt2 conversion causes an error when it is left empty. The code in txt1 works OK but I am asking is there a better way of coding this Public Class Main
3
52530
by: satyakarvvk | last post by:
Hi everybody! Please help me to overcome below runtime exception. Actually it is a simple program on basics. I want to print odd nos upto which the user asks and after printing the task, again i will ask user whether he want to continue again and the process is repeated. My code is working first time normally but after user says yes(y) for continuing again my code producing an error. The Integer.parseInt taking space as default...
0
9647
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
9491
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
10357
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
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7510
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4063
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
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.