LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-27-2011, 08:44 AM   #1
ahzeeper
LQ Newbie
 
Registered: Apr 2011
Posts: 11

Rep: Reputation: 0
Converting string sequence of 1's and 0's into their Hexa sequences


Hey all,
I have to write a code that converts a sequence of 1's and 0's(block) into their equivalent hexa number and copying to another array(byte). but this sequence is not always of length 8 and you are required to send strlen(sequence)%8 bits back into the string.
So i've written down this code and it works well with the sample input but fails in the real program.
Is there a smarter way of doing this?
thanks



Code:
int Convert_encode( char * block,unsigned char * byte)
{
 int len,iter,i,j,k,sum;
  char * temp=(char *)malloc(4*sizeof(char));
  len=strlen(block)/8;
  iter=strlen(block)/4;
  for (i=0;i<len;i++)
   {puts("a2");
   for(k=0;k<2;k++)    // this encodes first and last four bits seperatly    
   {
   sum=0;              //initializing sum
   for (j=0;j<4;j++)   //converting ASCII to 0-15 decimal
    {puts("a20");
    temp[j]=block[i*8+k*4+j]; puts("a21");
    if(temp[j]=='1')
    sum=sum+pow(2,3-j);
    } //puts("a3"); 
    printf("%d\n",sum);
   switch (sum)     // decimal to hexa
   {
   case 0:
   strcat(byte,"0");
   break;
   case 1:
   strcat(byte,"1");
   break;
   case 2:
   strcat(byte,"2");
   break;
   case 3:
   strcat(byte,"3");
   break;
   case 4:
   strcat(byte,"4");
   break;
   case 5:
   strcat(byte,"5");
   break;
   case 6:
   strcat(byte,"6");
   break;
   case 7:
   strcat(byte,"7");
   break;
   case 8:
   strcat(byte,"8");
   break;
   case 9:
   strcat(byte,"9");
   break;
   case 10:
   strcat(byte,"A");
   break;
   case 11:
   strcat(byte,"B");
   break;
   case 12:
   strcat(byte,"C");
   break;
   case 13:
   strcat(byte,"D");
   break;
   case 14:
   strcat(byte,"E");
   break;
   case 15:
   strcat(byte,"F");
   break;
   
   default :
   printf("unknown value in block\n");
   } 
    }
    } 
strcpy(block,&block[8*len]);
return(len);
free(temp);
}

Last edited by ahzeeper; 04-27-2011 at 09:30 AM.
 
Old 04-27-2011, 08:54 AM   #2
grail
LQ Guru
 
Registered: Sep 2009
Location: Perth
Distribution: Manjaro
Posts: 10,007

Rep: Reputation: 3191Reputation: 3191Reputation: 3191Reputation: 3191Reputation: 3191Reputation: 3191Reputation: 3191Reputation: 3191Reputation: 3191Reputation: 3191Reputation: 3191
Please use [code][/code] tags as this is almost illegible.
Quote:
but fails in the real program.
You would need to elaborate on what you mean by 'fails'?
 
Old 04-27-2011, 09:02 AM   #3
theNbomr
LQ 5k Club
 
Registered: Aug 2005
Distribution: OpenSuse, Fedora, Redhat, Debian
Posts: 5,399
Blog Entries: 2

Rep: Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908
Your code is hard to read, because you failed to post in [CODE][/CODE] tags. In general, each char can be treated as a binary digit, and each binary digit can be multiplied by its binary weight, and summed with the other weighted values. The weight can be iteratively computed by multiplying by two on each loop, where the loop iterates once for each digit in the string.
Once the binary value represented by the string has been fully computed, you can use printf() to re-display it in a hexadecimal radix.
Code:
weight = 1
sumOfBits = 0
for each ASCII digit
   if ASCII digit = '1' then
      sumOfBits = sumOfBits + weight
   end if
   weight = weight * 2
end for

printf( "%04X", sumOfBits )
Any integer data type will automatically be an even number of bytes (8-bits).

--- rod.

Last edited by theNbomr; 04-27-2011 at 10:13 AM.
 
Old 04-27-2011, 09:17 AM   #4
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
First, could you please edit your original post so that it includes formatted code placed within CODE tags? It would make it much easier to read your code.

Second, could you please confirm if it is C code you are developing? Some developers wish to develop in C++, but end up writing C code.

Lastly, what does your input look like? Is it like: "1010000111101000"? Is the length of the input string a multiple of 8 or 4? Four bits (half-byte or nibble) can easily be translated to hex.
 
Old 04-27-2011, 09:37 AM   #5
ahzeeper
LQ Newbie
 
Registered: Apr 2011
Posts: 11

Original Poster
Rep: Reputation: 0
Sorry for tags.

I am developing this code in C, no c++.
The input is a string of 1's and 0's but its length is not fixed. so it can be a multiple of 8 or not. but if it is not a multiple of eight then you take the remaining bits and copy them back into the original array ie block.
for instance lets say the block has '11110000101'. so now the "byte" should read F0 while the "block" output should be 101( these are the remainder of the bits that cant be converted).

This program is part of a JPEG encoder.
@dwhitney what is the easy method you are talking about?

thanks all
 
Old 04-27-2011, 09:52 AM   #6
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
Quote:
Originally Posted by ahzeeper View Post
This program is part of a JPEG encoder.
@dwhitney what is the easy method you are talking about?
See theNbomr's post for pseudocode that will help you with your algorithm.

Here's how I did the conversion in C++. However my code requires that the string have a length that is a multiple of 4. That's not a big deal; you can easily get the required nibbles using arithmetic; some number N div 4. Then copy that result multiplied by 4 to get the number of working digits; the remainder will be placed into your "output" buffer.

My code:
Code:
#include <iostream>
#include <string>
#include <cassert>
#include <cmath>

int main(int argc, char** argv)
{
   assert(argc == 2);

   std::string binstr = argv[1];

   assert(binstr.size() % 4 == 0);

   size_t pos = 0;

   while (pos != binstr.size())
   {
      std::string fourbits = binstr.substr(pos, 4);

      pos += 4;

      int sum = 0;

      for (size_t i = 0; i < 4; ++i)
      {
         if (int(fourbits[i] - '0') > 0)
         {
            sum += int(pow(double(2), double(3 - i)));
         }
      }

      std::cout << std::hex << sum;
   }
   std::cout << std::endl;
}

Last edited by dwhitney67; 04-27-2011 at 11:17 AM.
 
Old 04-27-2011, 10:12 AM   #7
ahzeeper
LQ Newbie
 
Registered: Apr 2011
Posts: 11

Original Poster
Rep: Reputation: 0
thanks
 
Old 04-27-2011, 10:22 AM   #8
ahzeeper
LQ Newbie
 
Registered: Apr 2011
Posts: 11

Original Poster
Rep: Reputation: 0
My code pretty much does the same thing, except after i convert it into a integer( between 0 and 15) i use switch case and strcat( ) to write equivalent hex values.
Anyways my code runs fine on the test samples but in the main program(which has been already written by someone else, and does'nt have any problems, that i know for sure) where i have to use this it gives me a segmentation fault. The error comes in a line where the HEX value of 4 is being written out by the strcat().
i'll post the error later
thanks again people
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Replacing a numeric string with a sequence of numbers ziggy25 Linux - Newbie 13 12-03-2009 10:18 AM
Converting string to char xfceslacker Programming 2 10-20-2006 05:15 PM
converting a int to string irfanhab Programming 6 07-30-2005 09:40 PM
converting string to asterisks pantera Programming 2 09-13-2004 01:27 PM
Converting a string from /etc/passwd liguorir Linux - Software 3 04-13-2004 02:32 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 03:18 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration