473,322 Members | 1,610 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

How to convert a byte array to a string?

Hello all,
I used multicasting and received compressed data packets over the network.I decompressed the packets at a specified memory block 'in'(declared as lzo_byte *in)....Now,i want to convert 'in' to a string and display the result on the console(and also save it on disk)...How do i do this?

Any help will be really useful....
Thanks in advance....Cheers
Feb 27 '07 #1
10 8522
horace1
1,510 Expert 1GB
Hello all,
I used multicasting and received compressed data packets over the network.I decompressed the packets at a specified memory block 'in'(declared as lzo_byte *in)....Now,i want to convert 'in' to a string and display the result on the console(and also save it on disk)...How do i do this?

Any help will be really useful....
Thanks in advance....Cheers
is the information in the bytes meaningful characters or integer numeric data?
The simplest thing is to have a for() loop go thru the array printing each element in the format you require.
Feb 27 '07 #2
Thanks for the quick response....
The memory block "in" has integar values as well as characters....I have already used a 'for()' loop while capturing the data packets.....so every element of 'in' is already accounted for...how do I write it in a file now?

Cheers
Feb 27 '07 #3
horace1
1,510 Expert 1GB
Thanks for the quick response....
The memory block "in" has integar values as well as characters....I have already used a 'for()' loop while capturing the data packets.....so every element of 'in' is already accounted for...how do I write it in a file now?

Cheers
you can open a file using fopen() in C
http://www.cplusplus.com/fopen

or ostream in C++
http://www.cplusplus.com/reference/iostream/

you can either write out binary information, e.g. your byte array, or the character and/or numeric text representation
http://tools.devshed.com/c/a/Web-Development/C-File-IO-and-Binary-File-IO/
http://www.cplusplus.com/doc/tutorial/files.html
Feb 27 '07 #4
Hi...
Yes,I tried using the fopen() way...but there was still some problems(the program got stuck just before the fwrite() function....the following is the relevant code snippet....I just cannot get where I am going wrong..:(


Expand|Select|Wrap|Line Numbers
  1. FILE *pdecompressed;
  2.          pdecompressed=fopen("C:\abc.txt","w");
  3.          fwrite((const void*)*in,sizeof(in[0]),sizeof(in),pdecompressed);
  4.          fclose(pdecompressed);
Apparently,it looks like the problem is in the fweite() statement.....

Cheers...
Feb 27 '07 #5
horace1
1,510 Expert 1GB
Hi...
Yes,I tried using the fopen() way...but there was still some problems(the program got stuck just before the fwrite() function....the following is the relevant code snippet....I just cannot get where I am going wrong..:(


Expand|Select|Wrap|Line Numbers
  1. FILE *pdecompressed;
  2.          pdecompressed=fopen("C:\abc.txt","w");
  3.          fwrite((const void*)*in,sizeof(in[0]),sizeof(in),pdecompressed);
  4.          fclose(pdecompressed);
Apparently,it looks like the problem is in the fweite() statement.....

Cheers...
to have a \ in a string up have to enter \\, e.g.
Expand|Select|Wrap|Line Numbers
  1.          pdecompressed=fopen("C:\\abc.txt","w");
  2.  
the fopen would have failed which is why the fwrite() fails - you should check that the fopen() worked
Feb 27 '07 #6
Hi...

the fopen() works(i have checked that)...but the prob is in the fwrite() part...
also,if I want to print the decompressed 'in' on the console,I think I'd have to use one infinite 'for' loop within another infinite 'for' loop..!That sounds impossible...I am at a loss....Here's my entire code:

Expand|Select|Wrap|Line Numbers
  1.  # include "StdAfx.h"
  2.  
  3. #include <winsock2.h>
  4. #include <ws2tcpip.h>
  5. #include <sys/types.h>  /* for type definitions */
  6.  
  7. #include <stdio.h>      /* for printf() and fprintf() */
  8.  
  9. #include <stdlib.h>     /* for atoi() */
  10.  
  11. #include <string.h>     /* for strlen() */
  12.  
  13. //#include "lzoconf.h"
  14.  
  15. #include <lzo1x.h>
  16.  
  17. /* portability layer */
  18.  
  19. //#define WANT_LZO_MALLOC 1
  20. //#include "portab.h"
  21.  
  22.  
  23. #define MAX_LEN  1024   /* maximum receive string size */ 
  24.  
  25. #define MIN_PORT 1024   /* minimum port allowed */
  26.  
  27. #define MAX_PORT 65535  /* maximum port allowed */
  28.  
  29. #ifndef IN_LEN
  30. #define IN_LEN      (128*1024L)
  31. #endif
  32. #define OUT_LEN     (IN_LEN + IN_LEN / 16 + 64 + 3)
  33.  
  34. #include "lutil.h"
  35.  
  36. #define lzo_init() __lzo_init2(LZO_VERSION,(int)sizeof(short),(int)sizeof(int),\
  37.     (int)sizeof(long),(int)sizeof(lzo_uint32),(int)sizeof(lzo_uint),\
  38.     (int)lzo_sizeof_dict_t,(int)sizeof(char *),(int)sizeof(lzo_voidp),\
  39.     (int)sizeof(lzo_compress_t))
  40. LZO_EXTERN(int) __lzo_init2(unsigned,int,int,int,int,int,int,int,int,int);
  41.  
  42. int main(int argc, char *argv[]) {
  43.  
  44.   //string str;
  45.  
  46.   //string port;
  47.  
  48.   int sock;                     /* socket descriptor */
  49.  
  50.   int flag_on = 1;              /* socket option flag */
  51.  
  52.   struct sockaddr_in mc_addr;   /* socket address structure */
  53.  
  54.   char recv_str[MAX_LEN+1];     /* buffer to receive string */
  55.  
  56.   int recv_len;                 /* length of string received */
  57.  
  58.   struct ip_mreq mc_req;        /* multicast request structure */
  59.  
  60.   char mc_addr_str[11]="225.0.0.36";            /* multicast IP address */
  61.  
  62.   int mc_port=15000;       /* multicast port */
  63.  
  64. //char mc_addr_str[11]="233.1.2.4";            /* multicast IP address */
  65.  
  66.  // int mc_port=6755;       /* multicast port */
  67.  
  68.  
  69.   struct sockaddr_in from_addr; /* packet source */
  70.  
  71.   int from_len;        /* source addr length */
  72.  
  73.   WSADATA wsaData; 
  74.  
  75.    /*Windows socket DLL structure */
  76.  
  77.     int r;
  78.     lzo_byte *in;
  79.     lzo_byte *out;
  80.     //lzo_bytep recv_str;
  81.     lzo_byte *wrkmem;
  82.     lzo_uint in_len;
  83.     lzo_uint recv_str_len;
  84.     lzo_uint new_len;
  85.     lzo_uint out_len;
  86.  
  87.  
  88.   /* validate number of arguments */
  89.  
  90.   if (argc != 3) {
  91.  
  92.     fprintf(stderr, 
  93.  
  94.             "Usage: %s <Multicast IP> <Multicast Port>\n", 
  95.  
  96.             argv[0]);
  97.  
  98.    // exit(1);
  99.  
  100.   }
  101.  
  102.  
  103.  
  104.   /* validate the port range */
  105.  
  106.   if ((mc_port < MIN_PORT) || (mc_port > MAX_PORT)) {
  107.  
  108.     fprintf(stderr, "Invalid port number argument %d.\n",
  109.  
  110.             mc_port);
  111.  
  112.     fprintf(stderr, "Valid range is between %d and %d.\n",
  113.  
  114.             MIN_PORT, MAX_PORT);
  115.  
  116.    // exit(1);
  117.  
  118.   }
  119.  
  120.  
  121.  
  122.   /* Load Winsock 2.0 DLL */
  123.  
  124.   if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
  125.  
  126.       fprintf(stderr, "WSAStartup() failed");
  127.  
  128.       //exit(1);
  129.  
  130.   }
  131.  
  132.  
  133.  
  134.   /* create socket to join multicast group on */
  135.  
  136.   if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
  137.  
  138.     perror("socket() failed");
  139.  
  140.     //exit(1);
  141.  
  142.   }
  143.  
  144.  
  145.  
  146.   /* set reuse port to on to allow multiple binds per host */
  147.  
  148.   if ((setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&flag_on,
  149.  
  150.        sizeof(flag_on))) < 0) {
  151.  
  152.     perror("setsockopt() failed");
  153.  
  154.      // exit(1);
  155.  
  156.   }
  157.  
  158.  
  159.  
  160.   /* construct a multicast address structure */
  161.  
  162.   memset(&mc_addr, 0, sizeof(mc_addr));
  163.  
  164.   mc_addr.sin_family      = AF_INET;
  165.  
  166.   mc_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  167.  
  168.   mc_addr.sin_port        = htons(mc_port);
  169.  
  170.  
  171.  
  172.   /* bind to multicast address to socket */
  173.  
  174.   if ((bind(sock, (struct sockaddr *) &mc_addr, 
  175.  
  176.        sizeof(mc_addr))) < 0) {
  177.  
  178.     perror("bind() failed");
  179.  
  180.     //exit(1);
  181.  
  182.   }
  183.  
  184.  
  185.  
  186.   /* construct an IGMP join request structure */
  187.  
  188.   mc_req.imr_multiaddr.s_addr = inet_addr(mc_addr_str);
  189.  
  190.   mc_req.imr_interface.s_addr = htonl(INADDR_ANY);
  191.  
  192.  
  193.  
  194.   /* send an ADD MEMBERSHIP message via setsockopt */
  195.  
  196.   if ((setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
  197.  
  198.        (char*) &mc_req, sizeof(mc_req))) < 0) {
  199.  
  200.     perror("setsockopt() failed");
  201.  
  202.    // exit(1);
  203.  
  204.   }
  205.  
  206.  
  207.     for (int i=0;i<2;i++){
  208.  // for (;;) {          /* loop forever */
  209.  
  210.  
  211.  
  212.     /* clear the receive buffers & structs */
  213.  
  214.     memset(recv_str, 0, sizeof(recv_str));
  215.  
  216.     from_len = sizeof(from_addr);
  217.  
  218.     memset(&from_addr, 0, from_len);
  219.  
  220.  
  221.  
  222.     /* block waiting to receive a packet */
  223.  
  224.     if ((recv_len = recvfrom(sock, recv_str, MAX_LEN, 0, 
  225.  
  226.          (struct sockaddr*)&from_addr, &from_len)) < 0) {
  227.  
  228.       perror("recvfrom() failed");
  229.  
  230.       exit(1);
  231.  
  232.     }
  233.  
  234.  
  235.  
  236.     /* output received string */
  237.  
  238.     printf("Received %d bytes from %s: ", recv_len, 
  239.  
  240.            inet_ntoa(from_addr.sin_addr));
  241.  
  242.    printf("%s", recv_str);
  243.     out=(unsigned char *)recv_str;
  244.  
  245.  
  246.    //////////////  end loop
  247. #if defined(_EMX_)
  248.   _response(&argc,&argv);
  249.   _wildcard(&argc,&argv);
  250. #endif
  251.  
  252.   if(argc<0 &&argv==NULL)
  253.       return 0;
  254.  
  255.   printf("\nLZO real-time data compression library(v%s,%s).\n",lzo_version_string(),lzo_version_date());
  256.   printf("Copyright (C)1996-2000 Markus Franz Xaver Johannes Oberhumer\n\n");
  257.  
  258.  
  259.  
  260.  
  261.  
  262. /*
  263.  * Step 1: initialize the LZO library
  264.  */
  265.  
  266.  if (lzo_init() != LZO_E_OK)
  267.     {
  268.         printf("internal error - lzo_init() failed !!!\n");
  269.         printf("(this usually indicates a compiler bug - try recompiling\nwithout optimizations, and enable `-DLZO_DEBUG' for diagnostics)\n");
  270.         //return 4;
  271.         printf("Step 1 complete.\n");
  272.     }
  273.  
  274.  
  275. /*
  276.  * Step 2: allocate blocks and the work-memory
  277.  */
  278.    in = (lzo_bytep) lzo_malloc(IN_LEN);
  279.     //out = (lzo_bytep) lzo_malloc(OUT_LEN);
  280.     wrkmem = (lzo_bytep) lzo_malloc(LZO1X_1_MEM_COMPRESS);
  281.     if (in == NULL || recv_str == NULL || wrkmem == NULL) 
  282.     {
  283.         printf("out of memory\n");
  284.         //return 3;
  285.      printf("Step 2 complete.\n");
  286.     }
  287.  
  288. /*
  289.  * Step 3: prepare the input block that will get compressed.
  290.  *         We just fill it with zeros in this example program,
  291.  *         but you would use your real-world data here.
  292.  */
  293.    in_len = IN_LEN;
  294.     //lzo_memset(in,packet,in_len);
  295.    lzo_memset(in,(int)recv_str,in_len);
  296.  
  297.  
  298.    //r=lzo1x_compress(in,in_len,out,&out_len,wrkmem)
  299.      //  if(r==LZO_E_OK)
  300.        //{printf("compressed \n",(long)in_len,(long)out_len)};
  301.  
  302.      /*
  303.  * Step 4: compress from `in' to `out' with LZO1X-1
  304.  */
  305.    r = lzo1x_1_compress((const unsigned char*)recv_str,recv_len,out,&out_len,wrkmem);
  306.  
  307.     if (r == LZO_E_OK)
  308.  
  309.         printf("compressed %lu bytes into %lu bytes  \n",
  310.             (long) recv_len, (long) out_len);
  311.     else
  312.     {
  313.         /* this should NEVER happen */
  314.         printf("internal error - compression failed: %d\n", r);
  315.         return 2;
  316.     }
  317.  
  318.  
  319.     /* check for an incompressible block */
  320.     /*if (out_len >= recv_len)
  321.     {
  322.         printf("This block contains incompressible data.\n");
  323.         return 0;
  324.     }
  325.  
  326. /*
  327.  * Step 5: decompress again, now going from `out' to `in'
  328.  */
  329.     r = lzo1x_decompress(out,out_len,in,&new_len,NULL);
  330.  
  331.     printf("Received Address is %u\n",recv_str);
  332.     printf("Out Address is %u\n",out);
  333.     printf("%ch     %ch      %ch      %ch    %ch\n",recv_str[20],recv_str[21],recv_str[22],recv_str[23],recv_str[24]);
  334.     printf("%ch     %ch      %ch      %ch    %ch\n",out[20],out[21],out[22],out[23],out[24]);
  335.     printf("%ch     %ch      %ch      %ch    %ch\n",in[20],in[21],in[22],in[23],in[24]);
  336.  
  337.     if (r == LZO_E_OK)
  338.         printf("decompressed %lu bytes back into %lu bytes \n",
  339.             (long) out_len, (long) in_len); 
  340.  
  341.     else
  342.     {
  343.         /* this should NEVER happen */
  344.         printf("internal error - decompression failed: %d\n", r);
  345.         return 1;
  346.     }
  347.  
  348.  
  349.  
  350.          FILE *pdecompressed;
  351.          pdecompressed=fopen("C:\\abc.txt","w");
  352.          fwrite((const void*)*in,sizeof(in[0]),sizeof(in),pdecompressed);
  353.          fclose(pdecompressed);
  354.  
  355.  
  356.     } ///For Loop end 
  357.     }
  358.  
  359.  
  360. /*
  361.  * Step 4: decompress again, now going from `out' to `in'
  362.  */
  363.     /*new_len = in_len;
  364.  
  365.        //r = lzo1x_decompress(out,recv_len,in,&new_len,NULL);
  366.  
  367.     r = lzo1x_decompress((const unsigned char *)recv_str,recv_len,in,&new_len,NULL);
  368.     if (r == LZO_E_OK && new_len == in_len)
  369.         printf("decompressed %lu bytes back into %lu bytes\n",
  370.             (unsigned long) recv_len, (unsigned long) in_len);
  371.  
  372.     else
  373.     {
  374.         /* this should NEVER happen */
  375.         /*printf("internal error - decompression failed: %d\n", r);
  376.         return 1;
  377.     }
  378.  
  379.  
  380.     lzo_free(wrkmem);
  381.     lzo_free(recv_str);
  382.     lzo_free(in);
  383.     printf("Simple compression test passed.\n");
  384.  
  385.     return 0; 
  386.  
  387.  
  388.   }
  389.  
  390.  // byte packet;
  391.   //  char  packet;
  392.   //packet=(char )recv_str;
  393.  
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.   /* send a DROP MEMBERSHIP message via setsockopt */
  401.  
  402.   /*if ((setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, 
  403.  
  404.        (const char*) &mc_req, sizeof(mc_req))) < 0) 
  405.   {
  406.     perror("setsockopt() failed");
  407.  
  408.     exit(1);
  409.  
  410. }
  411.  
  412.  
  413.   closesocket(sock);   
  414.  
  415.   WSACleanup();  /* Cleanup Winsock */
Kindly ignore the commented lines...I was trying different things to get rid of this problem...where am I wrong?The data receipt,compression and decompression works fine....but the decompressed o/ts can't be displayed...

Thanks for ur efforts...I appreciate it...

Cheers
Feb 27 '07 #7
horace1
1,510 Expert 1GB
as you are writing a binary file you should use mode wb, e.g.
Expand|Select|Wrap|Line Numbers
  1. pdecompressed=fopen("C:\\abc.txt","wb");
  2.  
Feb 27 '07 #8
I have tried that too :( :( It doesen't improve things....the peculiar thing is I just cannot get where the problem is(most probably in fwrite()..)Am i passing any wrong arguments in fwrite()...?

Cheers
Feb 27 '07 #9
Sebouh
78
I might be way over my head here, but i can't see where you have declared "in". You have defined it without declaring it.
Feb 27 '07 #10
Hi..
I have declared 'in' in Step 2 of the LZO algorithm...as follows:

Expand|Select|Wrap|Line Numbers
  1. in = (lzo_bytep) lzo_malloc(IN_LEN);
Still I can't solve this problem...

Thanks for ur efforts...Cheers..
Feb 27 '07 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Swarup | last post by:
I am reading a file (txt, xml, gif, ico, bmp etc) byte by byte and filling it into a byte arry. Now i have to convert it into a string to store it in the database. I use...
6
by: Ricardo Quintanilla | last post by:
i have a code that sends data to a socket listening over as400 platform, the socket responds to me as a "byte array". then i need to convert the "byte array" into a string. the problem is that...
15
by: Kueishiong Tu | last post by:
How do I convert a Byte array (unsigned char managed) to a char array(unmanaged) with wide character taken into account?
6
by: Allan Ebdrup | last post by:
How do I easily convert a int to a string? Kind Regards, Allan Ebdrup
6
by: moondaddy | last post by:
I'm writing an app in vb.net 1.1 and need to convert a byte array into a string, and then from a string back to a byte array. for example Private mByte() as New Byte(4){11,22,33,44} Now how...
6
by: Bob Altman | last post by:
Hi all, I'm looking for the fastest way to convert an array of bytes to String. I also need to convert a String back to its original Byte() representation. Convert.ToBase64String and...
12
by: Peter | last post by:
Trying to convert string to byte array. the following code returns byte array of {107, 62, 194, 139, 64} how can I convert this string to a byte array of {107, 62, 139, 65} ...
19
by: est | last post by:
From python manual str( ) Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that...
5
by: da1978 | last post by:
Hi experts, I need to convert a string or a Byte array to a string byte array. Its relatively easy to convert a string to an char array or a byte array but not a STRING byte array. i.e. ...
0
Debadatta Mishra
by: Debadatta Mishra | last post by:
Introduction In this article I will provide you an approach to manipulate an image file. This article gives you an insight into some tricks in java so that you can conceal sensitive information...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.