Converting string sequence of 1's and 0's into their Hexa sequences
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
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);
}
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).
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.
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?
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.
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
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.