0

I've to copy a std::string to ASCII ... but with only 7bit ASCII in memory. So this 8-Character string should fit into this 7-Byte/56Bit array.

std::string str = "12345678";
unsigned char ascii_destination[7];

I can grap every character from str and copy it with bit operations to its destinations but I was wondering if there is something more elegant to convert longer string to 7bit in memory? And I havn't found any built in functions for that... Thank you!

3
  • 1
    Outside of a std::bitset there aren't many easy way to manipulate bits besides working with data sized with full bytes directly and masking them to suit your needs. Commented Dec 17, 2015 at 14:12
  • 1
    What do you want to do with a string longer than 8 characters? It's impossible to compress it to 7 bytes. Maybe add an example? Commented Dec 17, 2015 at 14:21
  • 1
    What are you going to do with this 7bit ASCII string? You certainly can't send it to any computer outside a museum (all communication these days is in terms of octets - 8 bits of data at a time. It's quite common though for the range of values in the octet to be limited - for example to 7-bit ascii). Commented Dec 17, 2015 at 14:42

2 Answers 2

1

Since you have only 56 bits, you can use a 64-bit integer as intermediate storage:

uin64_t temp = 0;

// Add 7 bits to temp, 8 times
for (int i = 0; i < 8; ++i)
    temp = (temp << 7) | str[i];

// Remove 8 bits from temp, 7 times
for (int i = 0; i < 7; ++i)
{
    ascii_destination[i] = (uint8_t)(temp & 0xff);
    temp >>= 8;
}

(unless I understood completely wrong what you actually want)

Sign up to request clarification or add additional context in comments.

Comments

1

You probably mean MIME encoding where 7bit means that data is actually not encoded and is initially US ASCII. If it is not you can encode it in base64 and specify that encoding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.