Any way to create a char of size 32 in ANSI c?

399 views Asked by At

I know C++11 has a type char32_t that is 4 bytes, and I'm wondering if it's possible to implement something similar in C. The program I'm writing needs to have all char arrays be a multiple of 4 bytes.

2

There are 2 answers

2
Cloud On

How do you plan on working with this data? Will you only be using a single byte within the 32-bit variable, or will you be storing actual 32-bit data within it?

One simple solution would be to create your own abstract data type so you can change it later:

#include <stdint.h>
typedef int32_t mChar;
mChar myChar32Array[100]; // Allocates 100x32-bit values

There is a major pitfall with tinkering with char related data types though: a lot of libraries and code snippets in assume that a char is a char when working with text. If you plan on using string manipulation functions and expect them to work across multiple systems, you always declare strings as arrays of char, and never as signed char or unsigned char. The only time you should be using unsigned char is if you are working with 8-bit binary data directly and don't want to have to deal with unexpected oddities like sign extension, which will give you funky values if you aren't careful.

3
Antti Haapala -- Слава Україні On

C11 standard does support char32_t with strings encoded in UTF-32, for example:

#include <uchar.h>

int main() {
    char32_t *str = U"Hello world";
}

The program compiles cleanly with say gcc -std=c11.