I've been working with binary data and null bytes have really been screwing me up because I can't do strlen on them.
1. What is the best way to store binary data in C? As a char*?
2. How can you get the "length" of the binary data if it contains null bytes (in C)?
Binary Data
Started by John, Nov 24 2009 01:40 PM
8 replies to this topic
#1
Posted 24 November 2009 - 01:40 PM
|
|
|
#2
Posted 24 November 2009 - 02:20 PM
I'd handle it using a struct, where you use an integer to store the length and the char array. Basically, I'd steal from the C++ string implementation.
#3
Posted 24 November 2009 - 03:19 PM
#4
Posted 24 November 2009 - 03:49 PM
Like winged said, you use a variable to control the length of the data, as you use and you see in container classes. What exactly are you trying to do with your working with binary data? If you're working with structures maybe you should use sizeof operator to return the size of a structure.
#5
Posted 24 November 2009 - 04:06 PM
I think you should use a char array, and use sizeof to determine the size. Take a look at this example code:
#include <stdio.h>
int main()
{
char bin[]={1,0,1,0,1,1,0,1};
printf("%d\n", sizeof(bin));
return 0;
}
It stores some binary data in the bin array, and prints out how many bits it is.
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)
Download the new operating system programming kit! (some assembly required)
#6
Posted 24 November 2009 - 04:24 PM
Guest, in that situation it works, but when I pass bin to a function, it returns the sizeof the pointer.
#include <stdio.h>
void test(char *bin)
{
printf("%d\n", sizeof(bin));
}
int main()
{
char bin[]={1,0,1,0,1,1,0,1};
test(bin);
return 0;
}
#7
Posted 24 November 2009 - 04:34 PM
isn't it then you do
test(&bin);
or have I lost all memories from the pointers, references and stuff from C?
test(&bin);
or have I lost all memories from the pointers, references and stuff from C?
__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall
I study Information Systems at Karlstad University when I'm not on CodeCall
#8
Posted 24 November 2009 - 04:47 PM
When you read in data from a binary source, you should be using fread() already. If you do it like this:
size_t length = fread(myCharArray, 1, MY_CHAR_ARRAY_SIZE, readFile);You can save length in a struct to represent the size of the array being passed. That's the best I can come up with. :P Sorry I couldn't be any more helpful than WingedPanther already has.
Wow I changed my sig!
#9
Posted 25 November 2009 - 08:54 AM
Basically, as you add/remove data from your char array, you'll need to be also updating your length variable. Everything you do will have to be synchronized.


Sign In
Create Account

Back to top










